Example usage for java.util.stream Collectors toCollection

List of usage examples for java.util.stream Collectors toCollection

Introduction

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

Prototype

public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) 

Source Link

Document

Returns a Collector that accumulates the input elements into a new Collection , in encounter order.

Usage

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

public static <T> Set<T> getElementsById(Map<String, T> elements, Collection<String> ids) {
    return ids.stream().map(id -> elements.get(id)).filter(Objects::nonNull)
            .collect(Collectors.toCollection(LinkedHashSet::new));
}

From source file:org.dllearner.core.AnnComponentManager.java

/**
 * Get registered components which are of the specified type.
 *
 * @param type The super type./*  w w w  .j  a va2  s.co  m*/
 * @return All sub classes of type.
 */
public Collection<Class<? extends Component>> getComponentsOfType(Class type) {

    Collection<Class<? extends Component>> result = components.stream()
            .filter(component -> type.isAssignableFrom(component))
            .collect(Collectors.toCollection(ArrayList::new));

    return result;
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

private void searchIndexByPositionBlocking(String fieldName, String indexName, Integer start, Integer stop,
        AsyncResultHandler<List<String>> resultHandler) {
    redissonOther.getScoredSortedSet(getScoredSortedIndexKey(fieldName, indexName), StringCodec.INSTANCE)
            .valueRangeAsync(start, stop).addListener(future -> {
                Collection<String> res = (Collection<String>) future.get();
                try {
                    ArrayList<String> ids = res.stream().map(r -> lookupIdFromIndex(r, fieldName, indexName))
                            .collect(Collectors.toCollection(ArrayList::new));
                    resultHandler/*  w w w  .ja v a 2s.com*/
                            .handle(future.isSuccess()
                                    ? (future.get() != null ? Future.succeededFuture(ids)
                                            : Future.failedFuture(
                                                    new RepositoryException("No search result returned")))
                                    : Future.failedFuture(new RepositoryException(future.cause())));
                    if (future.isSuccess()) {
                        logger.debug("[" + getStorageKey() + "] Search Index By Position Success. Records: "
                                + ((Collection<String>) future.get()).size());
                    } else {
                        logger.debug("[" + getStorageKey() + "] Search Index By Position Failure.",
                                future.cause());
                    }
                } catch (RuntimeException e) {
                    resultHandler.handle(Future.failedFuture(e.getCause()));
                    logger.debug("[" + getStorageKey() + "] Search Index By Position Failure.", e);
                }
            });
}

From source file:io.tilt.minka.business.leader.distributor.Distributor.java

private void communicateUpdates() {
    final Set<ShardDuty> updates = partitionTable.getDutiesCrud().stream()
            .filter(i -> i.getDutyEvent() == DutyEvent.UPDATE && i.getState() == PREPARED)
            .collect(Collectors.toCollection(HashSet::new));
    if (!updates.isEmpty()) {
        for (ShardDuty updatedDuty : updates) {
            Shard location = partitionTable.getDutyLocation(updatedDuty);
            if (transport(updatedDuty, location)) {
                updatedDuty.registerEvent(SENT);
            }//from  w  w w  . jav a 2 s . c  o  m
        }
    }
}

From source file:net.sourceforge.pmd.util.fxdesigner.XPathPanelController.java

/**
 * Evaluate the contents of the XPath expression area
 * on the given compilation unit. This updates the xpath
 * result panel, and can log XPath exceptions to the
 * event log panel.//from w ww. j a v  a 2 s.  co  m
 *
 * @param compilationUnit The AST root
 * @param version         The language version
 */
public void evaluateXPath(Node compilationUnit, LanguageVersion version) {

    try {
        String xpath = getXpathExpression();
        if (StringUtils.isBlank(xpath)) {
            invalidateResults(false);
            return;
        }

        ObservableList<Node> results = FXCollections.observableArrayList(xpathEvaluator.evaluateQuery(
                compilationUnit, version, getXpathVersion(), xpath, ruleBuilder.getRuleProperties()));
        xpathResultListView.setItems(
                results.stream().map(parent::wrapNode).collect(Collectors.toCollection(LiveArrayList::new)));
        parent.highlightXPathResults(results);
        violationsTitledPane.setText("Matched nodes\t(" + results.size() + ")");
    } catch (XPathEvaluationException e) {
        invalidateResults(true);
        designerRoot.getLogger().logEvent(new LogEntry(e, Category.XPATH_EVALUATION_EXCEPTION));
    }

    xpathResultListView.refresh();

}

From source file:com.ge.predix.acs.service.policy.evaluation.PolicyEvaluationServiceTest.java

@Test
public void testPolicyEvaluationExceptionHandling() {
    List<PolicySet> twoPolicySets = createNotApplicableAndDenyPolicySets();
    when(this.policyService.getAllPolicySets()).thenReturn(twoPolicySets);
    when(this.policyMatcher.matchForResult(any(PolicyMatchCandidate.class), anyListOf(Policy.class)))
            .thenThrow(new RuntimeException("This policy matcher is designed to throw an exception."));

    PolicyEvaluationResult result = this.evaluationService.evalPolicy(createRequest("anyresource", "anysubject",
            "GET", Stream.of(twoPolicySets.get(0).getName(), twoPolicySets.get(1).getName())
                    .collect(Collectors.toCollection(LinkedHashSet::new))));

    Assert.assertEquals(result.getEffect(), Effect.INDETERMINATE);
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingGenerator.java

private void createSpeakerList(ConferenceSolution solution, int speakerListSize) {
    List<Speaker> speakerList = new ArrayList<>(speakerListSize);
    speakerNameGenerator.predictMaximumSizeAndReset(speakerListSize);
    for (int i = 0; i < speakerListSize; i++) {
        Speaker speaker = new Speaker();
        speaker.setId((long) i);
        speaker.setName(speakerNameGenerator.generateNextValue());
        Set<Timeslot> unavailableTimeslotSet;
        List<Timeslot> timeslotList = solution.getTimeslotList();
        if (random.nextDouble() < 0.10) {
            if (random.nextDouble() < 0.25) {
                // No mornings
                unavailableTimeslotSet = timeslotList.stream().filter(
                        timeslot -> timeslot.getStartDateTime().toLocalTime().isBefore(LocalTime.of(12, 0)))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            } else if (random.nextDouble() < 0.25) {
                // No afternoons
                unavailableTimeslotSet = timeslotList.stream().filter(
                        timeslot -> !timeslot.getStartDateTime().toLocalTime().isBefore(LocalTime.of(12, 0)))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            } else if (random.nextDouble() < 0.25) {
                // Only 1 day available
                LocalDate availableDate = timeslotList.get(random.nextInt(timeslotList.size())).getDate();
                unavailableTimeslotSet = timeslotList.stream()
                        .filter(timeslot -> !timeslot.getDate().equals(availableDate))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            } else {
                unavailableTimeslotSet = timeslotList.stream().filter(timeslot -> random.nextDouble() < 0.10)
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            }//from w  w  w. j  av  a  2 s .  c  o m
        } else {
            unavailableTimeslotSet = new LinkedHashSet<>(timeslotList.size());
        }
        speaker.setUnavailableTimeslotSet(unavailableTimeslotSet);
        speaker.setRequiredTimeslotTagSet(new LinkedHashSet<>());
        speaker.setPreferredTimeslotTagSet(new LinkedHashSet<>());
        speaker.setProhibitedTimeslotTagSet(new LinkedHashSet<>());
        speaker.setUndesiredTimeslotTagSet(new LinkedHashSet<>());
        Set<String> requiredRoomTagSet = new LinkedHashSet<>();
        for (Pair<String, Double> roomTagProbability : roomTagProbabilityList) {
            if (random.nextDouble() < roomTagProbability.getValue() / 20.0) {
                requiredRoomTagSet.add(roomTagProbability.getKey());
            }
        }
        speaker.setRequiredRoomTagSet(requiredRoomTagSet);
        Set<String> preferredRoomTagSet = new LinkedHashSet<>();
        for (Pair<String, Double> roomTagProbability : roomTagProbabilityList) {
            if (random.nextDouble() < roomTagProbability.getValue() / 10.0) {
                preferredRoomTagSet.add(roomTagProbability.getKey());
            }
        }
        speaker.setPreferredRoomTagSet(preferredRoomTagSet);
        speaker.setProhibitedRoomTagSet(new LinkedHashSet<>());
        speaker.setUndesiredRoomTagSet(new LinkedHashSet<>());
        logger.trace("Created speaker with name ({}).", speaker.getName());
        speakerList.add(speaker);
    }
    solution.setSpeakerList(speakerList);
}

From source file:eu.interedition.collatex.tools.CollationServer.java

private static Deque<String> path(Request request) {
    return Pattern.compile("/+").splitAsStream(Optional.ofNullable(request.getPathInfo()).orElse(""))
            .filter(s -> !s.isEmpty()).collect(Collectors.toCollection(ArrayDeque::new));
}

From source file:io.promagent.internal.HookMetadataParser.java

/**
 * Convert class file paths to class names and add them to result.
 *//*from   ww  w  .j  a v a  2s. c o  m*/
private static void addClassNames(Stream<String> paths, Collection<String> result,
        Predicate<String> classNameFilter) {
    paths.filter(name -> name.endsWith(".class"))
            .map(name -> name.substring(0, name.length() - ".class".length()))
            .map(name -> name.startsWith("/") ? name.substring(1) : name).map(name -> name.replace("/", "."))
            .filter(classNameFilter).collect(Collectors.toCollection(() -> result));
}

From source file:it.unibo.alchemist.model.implementations.environments.AbstractEnvironment.java

private ListSet<Node<T>> runQuery(final Position center, final double range) {
    final List<Node<T>> result = spatialIndex.query(center.buildBoundingBox(range).stream()
            .map(Position::getCartesianCoordinates).toArray(i -> new double[i][]));
    final int size = result.size();
    return ListSets
            .unmodifiableListSet(result.stream().filter(it -> getPosition(it).getDistanceTo(center) <= range)
                    .collect(Collectors.toCollection(() -> new ArrayListSet<>(size))));
}