Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

In this page you can find the example usage for java.util Set stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:dk.dma.ais.track.rest.resource.TrackResource.java

/** Create a Predicate<TargetInfo> out of user supplied mmsi and area information */
static Predicate<TargetInfo> createTargetFilterPredicate(Set<Integer> mmsis, Set<Area> baseAreas,
        Set<Area> areas) {
    Predicate<TargetInfo> mmsiPredicate = null;
    if (mmsis != null && mmsis.size() > 0) {
        mmsiPredicate = targetInfo -> mmsis.contains(targetInfo.getMmsi());
    }//from  www  . j a va2  s  .c o m

    Predicate<TargetInfo> baseAreaPredicate = null;
    if (baseAreas != null && baseAreas.size() > 0) {
        baseAreaPredicate = targetInfo -> baseAreas.stream()
                .anyMatch(area -> targetInfo.getPosition() != null && area.contains(targetInfo.getPosition()));
    }

    Predicate<TargetInfo> areaPredicate = null;
    if (areas != null && areas.size() > 0) {
        areaPredicate = targetInfo -> areas.stream()
                .anyMatch(area -> targetInfo.getPosition() != null && area.contains(targetInfo.getPosition()));
    }

    Predicate<TargetInfo> resultingAreaPredicate = null;
    if (baseAreaPredicate != null && areaPredicate == null) {
        resultingAreaPredicate = baseAreaPredicate;
    } else if (baseAreaPredicate != null && areaPredicate != null) {
        resultingAreaPredicate = baseAreaPredicate.and(areaPredicate);
    } else {
        resultingAreaPredicate = areaPredicate;
    }

    if (mmsiPredicate == null && resultingAreaPredicate == null)
        return t -> true;
    else if (mmsiPredicate != null && resultingAreaPredicate == null)
        return mmsiPredicate;
    else if (mmsiPredicate == null && resultingAreaPredicate != null)
        return resultingAreaPredicate;
    else
        return mmsiPredicate.or(resultingAreaPredicate);
}

From source file:act.installer.brenda.BrendaChebiOntology.java

/**
 * This function fetches and construct the set of main and direct applications for each ontology that has a role.
 * @param ontologyMap map {chebi id -> ChebiOntology object}
 * @param isSubtypeOfRelationships map {chebi id -> set of chebi id for its subtypes}
 * @param hasRoleRelationships map {chebi id -> set of chebi id for its roles}
 * @return a map from ChebiOntology objects to a ChebiApplicationSet object
 *//*from  w w  w  . ja  v a 2  s .  c  o  m*/
public static Map<ChebiOntology, ChebiApplicationSet> getApplications(Map<String, ChebiOntology> ontologyMap,
        Map<String, Set<String>> isSubtypeOfRelationships, Map<String, Set<String>> hasRoleRelationships) {

    Map<String, Set<String>> applicationToMainApplicationsMap = getApplicationToMainApplicationsMap(
            isSubtypeOfRelationships, APPLICATION_CHEBI_ID);

    // Filter out the roles that are not applications
    Map<String, Set<String>> directApplicationMap = new HashMap<>();
    hasRoleRelationships.forEach((key, value) -> directApplicationMap.put(key,
            value.stream().filter(ontology -> applicationToMainApplicationsMap.keySet().contains(ontology))
                    .collect(Collectors.toSet())));

    // Compute the set of main applications for each ontology that has a role (aka is a chemical entity).
    Map<ChebiOntology, Set<ChebiOntology>> chemicalEntityToMainApplicationMap = new HashMap<>();
    for (String chemicalEntity : directApplicationMap.keySet()) {

        Set<ChebiOntology> mainApplicationsSet = chemicalEntityToMainApplicationMap
                .get(ontologyMap.get(chemicalEntity));
        if (mainApplicationsSet == null) {
            mainApplicationsSet = new HashSet<>();
            chemicalEntityToMainApplicationMap.put(ontologyMap.get(chemicalEntity), mainApplicationsSet);
        }
        for (String parentApplication : directApplicationMap.get(chemicalEntity)) {
            Set<String> mainApplications = applicationToMainApplicationsMap.get(parentApplication);
            if (mainApplications != null) {
                mainApplicationsSet.addAll(mainApplications.stream().map(ontologyMap::get)
                        .filter(Objects::nonNull).collect(Collectors.toSet()));
            }
        }
    }

    // Finally, construct a ChebiApplicationSet object containing direct and main applications for the molecules.
    Map<ChebiOntology, ChebiApplicationSet> chemicalEntityToApplicationsMap = new HashMap<>();
    for (String chemicalEntity : directApplicationMap.keySet()) {
        Set<ChebiOntology> directApplications = directApplicationMap.get(chemicalEntity).stream()
                .map(ontologyMap::get).filter(Objects::nonNull).collect(Collectors.toSet());
        Set<ChebiOntology> mainApplications = chemicalEntityToMainApplicationMap
                .get(ontologyMap.get(chemicalEntity));
        if (directApplications.size() > 0 || mainApplications.size() > 0) {
            ChebiApplicationSet applications = new ChebiApplicationSet(directApplications, mainApplications);
            chemicalEntityToApplicationsMap.put(ontologyMap.get(chemicalEntity), applications);
        }
    }

    return chemicalEntityToApplicationsMap;
}

From source file:de.bund.bfr.knime.gis.views.canvas.CanvasUtils.java

public static <V extends Node> Set<Edge<V>> removeNodelessEdges(Set<Edge<V>> edges, Set<V> nodes) {
    Set<Edge<V>> removed = edges.stream()
            .filter(e -> !nodes.contains(e.getFrom()) || !nodes.contains(e.getTo()))
            .collect(Collectors.toCollection(LinkedHashSet::new));

    edges.removeAll(removed);/*  ww  w.j  a va2  s  .  co m*/

    return removed;
}

From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param commandId The id of the command that is registered with this cluster
 * @param statuses  The status of the cluster
 * @return The specification//from  ww w .  j  a  va2s.c  om
 */
public static Specification<ClusterEntity> findClustersForCommand(final String commandId,
        @Nullable final Set<ClusterStatus> statuses) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands);

        predicates.add(cb.equal(commands.get(CommandEntity_.uniqueId), commandId));

        if (statuses != null && !statuses.isEmpty()) {
            //Could optimize this as we know size could use native array
            predicates.add(
                    cb.or(statuses.stream().map(status -> cb.equal(root.get(ClusterEntity_.status), status))
                            .toArray(Predicate[]::new)));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:com.netflix.genie.core.jpa.specifications.JpaClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param commandId The id of the command that is registered with this cluster
 * @param statuses  The status of the cluster
 * @return The specification/*from ww w.  j ava  2s . com*/
 */
public static Specification<ClusterEntity> findClustersForCommand(final String commandId,
        final Set<ClusterStatus> statuses) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands);

        predicates.add(cb.equal(commands.get(CommandEntity_.id), commandId));

        if (statuses != null && !statuses.isEmpty()) {
            //Could optimize this as we know size could use native array
            final List<Predicate> orPredicates = statuses.stream()
                    .map(status -> cb.equal(root.get(ClusterEntity_.status), status))
                    .collect(Collectors.toList());
            predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:delfos.dataset.util.DatasetPrinter.java

public static String printCompactMatrix(Map<Object, Map<Object, String>> matrix) {

    StringBuilder str = new StringBuilder();

    Set<Object> rowKeys = matrix.keySet();
    Set<Object> colKeys = new TreeSet<>();
    for (Object rowKey : rowKeys) {
        colKeys.addAll(matrix.get(rowKey).keySet());
    }/* www.  ja  va  2 s.co  m*/

    //Escribo la cabecera, para los nombres de las columnas
    {
        str.append("|\t|");
        colKeys.stream().forEach((colKey) -> {
            str.append(colKey).append("\t|");
        });
        str.append("\n");

        str.append("+-------+");
        colKeys.stream().forEach((colKey) -> {
            str.append("-------+");
        });
        str.append("\n");
    }
    //Escribo cada lnea
    for (Object rowKey : rowKeys) {
        str.append("|").append(rowKey).append("\t|");
        for (Object colKey : colKeys) {
            if (matrix.get(rowKey).containsKey(colKey)) {
                String cellValue = matrix.get(rowKey).get(colKey);
                str.append(" ").append(cellValue).append(" \t|");
            } else {
                str.append("   \t|");
            }
        }
        str.append("\n");
    }

    //Cierro la tabla
    str.append("+-------+");
    colKeys.stream().forEach((colKey) -> {
        str.append("-------+");
    });
    str.append("\n");

    return str.toString();
}

From source file:io.divolte.server.recordmapping.ConfigRecordMapper.java

private static List<FieldSetter> setterListFromConfig(final Schema schema, final Config config) {
    if (!config.hasPath("divolte.tracking.schema_mapping.fields")) {
        throw new SchemaMappingException("Schema mapping configuration has no field mappings.");
    }//w  w  w.  java 2s .co m

    final Set<Entry<String, ConfigValue>> entrySet = config.getConfig("divolte.tracking.schema_mapping.fields")
            .root().entrySet();

    return entrySet.stream().map((e) -> fieldSetterFromConfig(schema, e))
            .collect(Collectors.toCollection(() -> new ArrayList<>(entrySet.size())));
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_Buckets.java

/** Want to end up with 3 lists:
 *  - v1 sources that don't exist in v2 (Create them)
 *  - v2 sources that don't exist in v1 (Delete them)
 *  - matching v1/v2 sources with different modified times (Update them)
 * @param to_compare/* w w  w  .j a  va  2 s  . c  o m*/
 * @returns a 3-tuple with "to create", "to delete", "to update"
 */
protected static Tuple3<Collection<String>, Collection<String>, Collection<String>> compareSourcesToBuckets_categorize(
        final Tuple2<Map<String, String>, Map<String, Date>> to_compare) {

    // Want to end up with 3 lists:
    // - v1 sources that don't exist in v2 (Create them)
    // - v2 sources that don't exist in v1 (Delete them)
    // - matching v1/v2 sources with different modified times (Update them)

    // (do delete first, then going to filter to_compare._1() on value==null)      
    final Set<String> v2_not_v1 = new HashSet<String>(to_compare._2().keySet());
    v2_not_v1.removeAll(to_compare._1().keySet());

    // OK not worried about deletes any more, not interested in isApproved:false

    final Set<String> to_compare_approved = to_compare._1().entrySet().stream()
            .filter(kv -> null != kv.getValue() && !kv.getValue().isEmpty()).map(kv -> kv.getKey())
            .collect(Collectors.toSet());

    final Set<String> v1_and_v2 = new HashSet<String>(to_compare_approved);
    v1_and_v2.retainAll(to_compare._2().keySet());

    final List<String> v1_and_v2_mod = v1_and_v2.stream().filter(id -> {
        try {
            final Date v1_date = parseJavaDate(to_compare._1().get(id));
            final Date v2_date = to_compare._2().get(id);
            return v1_date.getTime() > v2_date.getTime();
        } catch (Throwable e) {
            return false; // (just ignore)
        }
    }).collect(Collectors.toList());

    final Set<String> v1_not_v2 = new HashSet<String>(to_compare_approved);
    v1_not_v2.removeAll(to_compare._2().keySet());

    return Tuples._3T(v1_not_v2, v2_not_v1, v1_and_v2_mod);
}

From source file:net.lldp.checksims.ChecksimsRunner.java

/**
 * Main public entrypoint to Checksims. Runs similarity detection according to given configuration.
 *
 * @param config Configuration defining how Checksims will be run
 * @return Map containing output of all output printers requested. Keys are name of output printer.
 * @throws ChecksimsException Thrown on error performing similarity detection
 *//*from  ww w .  j  a  va 2 s  .com*/
public static ImmutableMap<String, String> runChecksims(ChecksimsConfig config) throws ChecksimsException {
    checkNotNull(config);

    // Create a logger to log activity
    Logger logs = LoggerFactory.getLogger(ChecksimsRunner.class);

    // Set parallelism
    int threads = config.getNumThreads();
    ParallelAlgorithm.setThreadCount(threads);
    // TODO following line may not be necessary as we no longer use parallel streams?
    System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "" + threads);

    ImmutableSet<Submission> submissions = config.getSubmissions();

    logs.info("Got " + submissions.size() + " submissions to test.");

    ImmutableSet<Submission> archiveSubmissions = config.getArchiveSubmissions();

    if (!archiveSubmissions.isEmpty()) {
        logs.info("Got " + archiveSubmissions.size() + " archive submissions to test.");
    }

    if (submissions.size() == 0) {
        throw new ChecksimsException("No student submissions were found - cannot run Checksims!");
    }

    // Apply all preprocessors
    for (SubmissionPreprocessor p : config.getPreprocessors()) {
        submissions = ImmutableSet
                .copyOf(PreprocessSubmissions.process(p, submissions, config.getStatusLogger()));

        if (!archiveSubmissions.isEmpty()) {
            archiveSubmissions = ImmutableSet
                    .copyOf(PreprocessSubmissions.process(p, archiveSubmissions, config.getStatusLogger()));
        }
    }

    if (submissions.size() < 2) {
        throw new ChecksimsException("Did not get at least 2 student submissions! Cannot run Checksims!");
    }

    // Apply algorithm to submissions
    Set<Pair<Submission, Submission>> allPairs = PairGenerator.generatePairsWithArchive(submissions,
            archiveSubmissions);
    Set<AlgorithmResults> results = AlgorithmRunner.runAlgorithm(allPairs, config.getAlgorithm(),
            config.getStatusLogger());

    if (config.isIgnoringInvalid()) {
        Set<Submission> validSubmissions = new HashSet<>();
        Set<Submission> validArchivedSubmissions = new HashSet<>();
        Set<AlgorithmResults> validResults = new HashSet<>();
        submissions.stream().filter(S -> !S.testFlag("invalid")).forEach(S -> validSubmissions.add(S));
        archiveSubmissions.stream().filter(S -> !S.testFlag("invalid"))
                .forEach(S -> validArchivedSubmissions.add(S));
        results.stream().filter(S -> S.isValid()).forEach(S -> validResults.add(S));

        submissions = ImmutableSet.copyOf(validSubmissions);
        archiveSubmissions = ImmutableSet.copyOf(validArchivedSubmissions);
        results = validResults;

    }

    SimilarityMatrix resultsMatrix = SimilarityMatrix.generateMatrix(submissions, archiveSubmissions, results);

    // All parallel jobs are done, shut down the parallel executor
    ParallelAlgorithm.shutdownExecutor();
    config.getStatusLogger().end();

    Map<String, String> outputMap = new HashMap<>();

    // Output using all output printers
    for (MatrixPrinter p : config.getOutputPrinters()) {
        logs.info("Generating " + p.getName() + " output");

        outputMap.put(p.getName(), p.printMatrix(resultsMatrix));
    }

    ChecksimsCommandLine.deleteTempFiles();

    return ImmutableMap.copyOf(outputMap);
}

From source file:com.willwinder.universalgcodesender.gcode.GcodeParser.java

/**
 * Process commend given an initial state. This method will not modify its
 * input parameters.//from w ww . j  ava 2 s . co m
 * 
 * @param includeNonMotionStates Create gcode meta responses even if there is no motion, for example "F100" will not
 * return a GcodeMeta entry unless this flag is set to true.
 */
public static List<GcodeMeta> processCommand(String command, int line, final GcodeState inputState,
        boolean includeNonMotionStates) throws GcodeParserException {
    List<String> args = GcodePreprocessorUtils.splitCommand(command);
    if (args.isEmpty())
        return null;

    // Initialize with original state
    GcodeState state = inputState.copy();

    state.commandNumber = line;

    // handle M codes.
    //codes = GcodePreprocessorUtils.parseCodes(args, 'M');
    //handleMCode(for each codes);

    List<String> fCodes = GcodePreprocessorUtils.parseCodes(args, 'F');
    if (!fCodes.isEmpty()) {
        try {
            state.speed = Double.parseDouble(Iterables.getOnlyElement(fCodes));
        } catch (IllegalArgumentException e) {
            throw new GcodeParserException("Multiple F-codes on one line.");
        }
    }

    List<String> sCodes = GcodePreprocessorUtils.parseCodes(args, 'S');
    if (!sCodes.isEmpty()) {
        try {
            state.spindleSpeed = Double.parseDouble(Iterables.getOnlyElement(sCodes));
        } catch (IllegalArgumentException e) {
            throw new GcodeParserException("Multiple S-codes on one line.");
        }
    }

    // Gather G codes.
    Set<Code> gCodes = GcodePreprocessorUtils.getGCodes(args);

    boolean hasAxisWords = GcodePreprocessorUtils.hasAxisWords(args);

    // Error to mix group 1 (Motion) and certain group 0 (NonModal) codes (G10, G28, G30, G92)
    Collection<Code> motionCodes = gCodes.stream().filter(c -> c.consumesMotion()).collect(Collectors.toList());

    // 1 motion code per line.
    if (motionCodes.size() > 1) {
        throw new GcodeParserException(Localization.getString("parser.gcode.multiple-axis-commands") + ": "
                + StringUtils.join(motionCodes, ", "));
    }

    // If there are axis words and nothing to use them, add the currentMotionMode.
    if (hasAxisWords && motionCodes.isEmpty() && state.currentMotionMode != null) {
        gCodes.add(state.currentMotionMode);
    }

    // Apply each code to the state.
    List<GcodeMeta> results = new ArrayList<>();
    for (Code i : gCodes) {
        if (i == UNKNOWN) {
            logger.warning("An unknown gcode command was detected in: " + command);
        } else {
            GcodeMeta meta = handleGCode(i, args, line, state, hasAxisWords);
            meta.command = command;
            // Commands like 'G21' don't return a point segment.
            if (meta.point != null) {
                meta.point.setSpeed(state.speed);
            }
            results.add(meta);
        }
    }

    // Return updated state / command.
    if (results.isEmpty() && includeNonMotionStates) {
        GcodeMeta meta = new GcodeMeta();
        meta.state = state;
        meta.command = command;
        meta.code = state.currentMotionMode;
        return Collections.singletonList(meta);
    }

    return results;
}