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:com.github.drbookings.ui.controller.StatsViewController.java

private void updateUI(final BookingsByOrigin<BookingEntry> bookings, final Range<LocalDate> dateRange) {
    if (logger.isDebugEnabled()) {
        logger.debug("Statistics for\n" + BookingEntries.toBookings(bookings.getAllBookings()).stream()
                .map(i -> i.toString()).collect(Collectors.joining("\n")));
    }//from w  w  w  . j a va 2 s  .  c om
    final float allAllNigths = BookingEntries.countNights(bookings, false);
    final NavigableSet<LocalDate> allDates = bookings.getAllBookings(true).stream().map(b -> b.getDate())
            .collect(Collectors.toCollection(TreeSet::new));
    long monthCount = TemporalQueries.countOccurrences(allDates,
            SettingsManager.getInstance().getFixCostsPaymentDay());
    if (logger.isDebugEnabled()) {
        logger.debug("Month count: " + monthCount);
    }
    if (monthCount < 1) {
        monthCount = 1;
        if (logger.isDebugEnabled()) {
            logger.debug("Month count (corrected): " + monthCount);
        }
    }
    final float additionalCosts = SettingsManager.getInstance().getAdditionalCosts() * monthCount;
    final float numberOfRooms = SettingsManager.getInstance().getNumberOfRooms();
    final float totalAdditionalCosts = additionalCosts * numberOfRooms;
    if (logger.isDebugEnabled()) {
        logger.debug("Fix costs total: " + totalAdditionalCosts);
    }
    for (final Entry<BookingOrigin, Collection<BookingEntry>> e : bookings.getMap().entrySet()) {

        final Collection<? extends BookingEntry> bookingsFilteredByPaymentDate = e.getValue().stream()
                .filter(new PaymentDateFilter(dateRange)).collect(Collectors.toList());

        final Collection<? extends BookingEntry> bookingsFilteredByCleaningDate = e.getValue().stream()
                .filter(new CleaningDateFilter(dateRange)).collect(Collectors.toList());

        final int numberOfAllBookings = (int) BookingEntries.countBookings(new BookingsByOrigin<>(e.getValue()),
                false);

        final int numberOfPayedBookings = (int) BookingEntries
                .countBookings(new BookingsByOrigin<>(e.getValue()), false);

        final int numberOfAllNights = (int) BookingEntries.countNights(new BookingsByOrigin<>(e.getValue()),
                false);

        final int numberOfPayedNights = (int) BookingEntries
                .countNights(new BookingsByOrigin<>(bookingsFilteredByPaymentDate), false);

        final float percentage;

        if (StringUtils.isBlank(e.getKey().getName())) {
            percentage = 0;
        } else {
            percentage = numberOfAllNights / allAllNigths * 100f;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " percentage of all nights: " + percentage);
        }
        final double relativeFixCosts = totalAdditionalCosts * percentage / 100;
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " relative fix costs " + relativeFixCosts);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " number of bookings (all/payed): " + numberOfAllBookings + "/"
                    + numberOfPayedBookings);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + ": Number of nights (all/payed): " + numberOfAllNights + "/"
                    + numberOfPayedNights);
        }

        if (logger.isDebugEnabled()) {
            Set<Guest> set = e.getValue().stream().map(b -> b.getElement().getGuest())
                    .collect(Collectors.toCollection(LinkedHashSet::new));
            List<Guest> list = e.getValue().stream().filter(b -> !b.isCheckOut())
                    .map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
            StringBuilder sb = new StringBuilder(e.getKey() + " guest and nights (all):");
            int cnt = 1;
            int cnt2 = 0;
            for (final Guest guest : set) {
                final int cnt3 = Collections.frequency(list, guest);

                sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
                cnt2 += cnt3;
            }
            sb.append(String.format("%n%24s%4d", "Total", cnt2));

            logger.debug(sb.toString());

            set = bookingsFilteredByPaymentDate.stream().map(b -> b.getElement().getGuest())
                    .collect(Collectors.toCollection(LinkedHashSet::new));
            list = bookingsFilteredByPaymentDate.stream().filter(b -> !b.isCheckOut())
                    .map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
            sb = new StringBuilder(e.getKey() + " guest and nights (payed):");
            cnt = 1;
            cnt2 = 0;
            for (final Guest guest : set) {
                final int cnt3 = Collections.frequency(list, guest);

                sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
                cnt2 += cnt3;
            }
            sb.append(String.format("%n%24s%4d", "Total", cnt2));

            logger.debug(sb.toString());

        }

        final StatisticsTableBean b = StatisticsTableBean.build(e.getKey().getName(),
                bookingsFilteredByPaymentDate);
        StatisticsTableBean.applyCleaningStuff(b, bookingsFilteredByCleaningDate);
        b.setFixCosts((float) relativeFixCosts);
        b.setNightsPercent(percentage);
        b.setNumberOfPayedNights(numberOfPayedNights);
        b.setNumberOfAllNights(numberOfAllNights);
        b.setNumberOfPayedBookings(numberOfPayedBookings);
        b.setNumberOfAllBookings(numberOfAllBookings);
        data.add(b);
    }
    // add a total row

    final float relativeFixCosts = totalAdditionalCosts;
    final StatisticsTableBean b = StatisticsTableBean.buildSum(data);
    b.setFixCosts(relativeFixCosts);
    b.setNightsPercent(100);
    data.add(b);
}

From source file:org.mycore.common.MCRUtils.java

/**
 * merges to HashSets of MyCoreIDs after specific rules
 * /*from ww  w  .  j a v a2s  .  c  om*/
 * @see #COMMAND_OR
 * @see #COMMAND_AND
 * @see #COMMAND_XOR
 * @param set1
 *            1st HashSet to be merged
 * @param set2
 *            2nd HashSet to be merged
 * @param operation
 *            available COMMAND_XYZ
 * @return merged HashSet
 * @deprecated use {@link Stream}s for this
 */
@Deprecated
public static <T> HashSet<T> mergeHashSets(HashSet<? extends T> set1, HashSet<? extends T> set2,
        char operation) {
    Predicate<T> inSet1 = set1::contains;
    Predicate<T> inSet2 = set2::contains;
    Predicate<T> op;

    switch (operation) {
    case COMMAND_OR:
        op = t -> true;//inSet1.or(inSet2);
        break;

    case COMMAND_AND:
        op = inSet1.and(inSet2);
        break;

    case COMMAND_XOR:
        op = inSet1.and(inSet2).negate();
        break;

    default:
        throw new IllegalArgumentException("operation not permited: " + operation);
    }

    return Stream.concat(set1.stream(), set2.stream()).filter(op)
            .collect(Collectors.toCollection(HashSet::new));
}

From source file:gr.cti.android.experimentation.controller.api.SmartphoneController.java

private TreeSet<UsageEntry> extractUsageTimes(final Set<Result> results) {
    final Map<String, Long> res = new TreeMap<>();
    final SortedSet<Long> timestamps = results.stream().map(Result::getTimestamp)
            .collect(Collectors.toCollection(TreeSet::new));
    DateTime start = null;//from   w  w w.  j a  v  a2s.c o m
    DateTime lastDay = null;
    for (final Long timestamp : timestamps) {
        final DateTime curDateTime = new DateTime(timestamp);
        if (start == null) {
            start = new DateTime(timestamp);
        } else {
            if (start.withMillisOfDay(0).getMillis() == curDateTime.withMillisOfDay(0).getMillis()) {
                lastDay = new DateTime(timestamp);
            } else {
                if (lastDay != null) {
                    long diff = (lastDay.getMillis() - start.getMillis()) / 1000 / 60;
                    res.put(dfDay.format(lastDay.withMillisOfDay(0).getMillis()), diff);
                }
                start = null;
                lastDay = null;
            }
        }
    }

    return res.keySet().stream().map(dateKey -> new UsageEntry(dateKey, res.get(dateKey)))
            .collect(Collectors.toCollection(TreeSet::new));
}

From source file:com.ge.predix.integration.test.PolicyEvaluationCachingIT.java

/**
 * This test makes sure that cached policy evaluation results are properly invalidated when one of the policies in
 * a multiple policy set evaluation order list changes.
 * // w ww  . j  a v  a 2s .  c o  m
 */
@Test
public void testPolicyEvalCacheWithMultiplePolicySets() throws Exception {

    String indeterminatePolicyFile = "src/test/resources/policies/indeterminate.json";
    String denyAllPolicyFile = "src/test/resources/policies/deny-all.json";
    String siteBasedPolicyFile = "src/test/resources/policies/single-site-based.json";
    String endpoint = this.acsUrl;

    this.privilegeHelper.putSubject(this.acsAdminRestTemplate, MARISSA_V1, endpoint, this.acsZone1Headers,
            this.privilegeHelper.getDefaultAttribute());

    String indeterminatePolicySet = this.policyHelper.setTestPolicy(this.acsAdminRestTemplate,
            this.acsZone1Headers, endpoint, indeterminatePolicyFile);
    String denyAllPolicySet = this.policyHelper.setTestPolicy(this.acsAdminRestTemplate, this.acsZone1Headers,
            endpoint, denyAllPolicyFile);

    // test with a valid policy set evaluation order list
    PolicyEvaluationRequestV1 policyEvaluationRequest = this.policyHelper.createMultiplePolicySetsEvalRequest(
            MARISSA_V1.getSubjectIdentifier(), "sanramon", Stream.of(indeterminatePolicySet, denyAllPolicySet)
                    .collect(Collectors.toCollection(LinkedHashSet::new)));

    ResponseEntity<PolicyEvaluationResult> postForEntity = this.acsAdminRestTemplate.postForEntity(
            endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH,
            new HttpEntity<>(policyEvaluationRequest, this.acsZone1Headers), PolicyEvaluationResult.class);

    Assert.assertEquals(postForEntity.getStatusCode(), HttpStatus.OK);
    PolicyEvaluationResult responseBody = postForEntity.getBody();
    Assert.assertEquals(responseBody.getEffect(), Effect.DENY);

    // test with one of the policy sets changed from the evaluation order list
    String siteBasedPolicySet = this.policyHelper.setTestPolicy(this.acsAdminRestTemplate, this.acsZone1Headers,
            endpoint, siteBasedPolicyFile);
    policyEvaluationRequest = this.policyHelper.createMultiplePolicySetsEvalRequest(
            MARISSA_V1.getSubjectIdentifier(), "sanramon", Stream.of(indeterminatePolicySet, siteBasedPolicySet)
                    .collect(Collectors.toCollection(LinkedHashSet::new)));

    postForEntity = this.acsAdminRestTemplate.postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH,
            new HttpEntity<>(policyEvaluationRequest, this.acsZone1Headers), PolicyEvaluationResult.class);

    Assert.assertEquals(postForEntity.getStatusCode(), HttpStatus.OK);
    responseBody = postForEntity.getBody();
    Assert.assertEquals(responseBody.getEffect(), Effect.PERMIT);

}

From source file:com.pwn9.PwnFilter.minecraft.PwnFilterPlugin.java

/**
 * <p>updateMetrics.</p>/*from  www  . ja v  a 2s .  co m*/
 */
public void updateMetrics() {
    ArrayList<String> activeListenerNames = FilterEngine.getInstance().getActiveClients().stream()
            .map(FilterClient::getShortName).collect(Collectors.toCollection(ArrayList::new));

    // Remove old plotters
    eventGraph.getPlotters().stream().filter(p -> !activeListenerNames.contains(p.getColumnName()))
            .forEach(p -> eventGraph.removePlotter(p));

    // Add new plotters
    for (final FilterClient f : FilterEngine.getInstance().getActiveClients()) {
        final String eventName = f.getShortName();
        eventGraph.addPlotter(new Metrics.Plotter(eventName) {
            @Override
            public int getValue() {
                RuleChain r = f.getRuleChain();
                if (r != null) {
                    return r.ruleCount(); // Number of rules for this event type
                } else
                    return 0;
            }
        });
    }
}

From source file:org.apache.samza.zk.ZkUtils.java

/**
 * Determines the validity of processor registered with zookeeper.
 *
 * If there are multiple processors registered with same processorId,
 * the processor with lexicographically smallest zookeeperPath is considered valid
 * and all the remaining processors are invalid.
 *
 * Two processors will not have smallest zookeeperPath because of sequentialId guarantees
 * of zookeeper for ephemeral nodes.//from   w  w w.  j a  v  a2 s. c  o  m
 *
 * @param processor to check for validity condition in processors group.
 * @return true if the processor is valid. false otherwise.
 */
private boolean isValidRegisteredProcessor(final ProcessorNode processor) {
    String processorId = processor.getProcessorData().getProcessorId();
    List<ProcessorNode> processorNodes = getAllProcessorNodes().stream()
            .filter(processorNode -> processorNode.processorData.getProcessorId().equals(processorId))
            .collect(Collectors.toList());
    // Check for duplicate processor condition(if more than one processor exist for this processorId).
    if (processorNodes.size() > 1) {
        // There exists more than processor for provided `processorId`.
        LOG.debug("Processor nodes in zookeeper: {} for processorId: {}.", processorNodes, processorId);
        // Get all ephemeral processor paths
        TreeSet<String> sortedProcessorPaths = processorNodes.stream().map(ProcessorNode::getEphemeralPath)
                .collect(Collectors.toCollection(TreeSet::new));
        // Check if smallest path is equal to this processor's ephemeralPath.
        return sortedProcessorPaths.first().equals(processor.getEphemeralPath());
    }
    // There're no duplicate processors. This is a valid registered processor.
    return true;
}

From source file:io.tilt.minka.business.leader.Shepherd.java

private ShardState evaluateStateThruHeartbeats(Shard shard) {
    final long now = System.currentTimeMillis();
    final long normalDelay = config.getFollowerHeartbeatDelayMs();
    final long configuredLapse = config.getShepherdHeartbeatLapseSec() * 1000;
    final long lapseStart = now - configuredLapse;
    //long minMandatoryHBs = configuredLapse / normalDelay;

    final ShardState currentState = shard.getState();
    ShardState newState = currentState;/*from w ww . ja v a  2 s .co m*/
    final List<Heartbeat> all = shard.getHeartbeats();
    List<Heartbeat> pastLapse = null;
    String msg = "";

    final int minHealthlyToGoOnline = config.getShepherdMinHealthlyHeartbeatsForShardOnline();
    final int minToBeGone = config.getShepherdMaxAbsentHeartbeatsBeforeShardGone();
    final int maxSickToGoQuarantine = config.getShepherdMaxSickHeartbeatsBeforeShardQuarantine();

    if (all.size() < minToBeGone) {
        if (shard.getLastStatusChange().plus(config.getShepherdMaxShardJoiningStateMs()).isBeforeNow()) {
            msg = "try joining expired";
            newState = ShardState.GONE;
        } else {
            msg = "no enough heartbeats in lapse";
            newState = ShardState.JOINING;
        }
    } else {
        pastLapse = all.stream().filter(i -> i.getCreation().isAfter(lapseStart))
                .collect(Collectors.toCollection(ArrayList::new));
        int pastLapseSize = pastLapse.size();
        if (pastLapseSize > 0 && checkHealth(now, normalDelay, pastLapse)) {
            if (pastLapseSize >= minHealthlyToGoOnline) {
                msg = "healthy lapse > = min. healthly for online";
                newState = ShardState.ONLINE;
            } else {
                msg = "healthly lapse < min. healthly for online";
                newState = ShardState.QUARANTINE;
                // TODO cuantas veces soporto que flapee o que este Quarantine antes de matarlo x forro ?
            }
        } else {
            if (pastLapseSize > maxSickToGoQuarantine) {
                if (pastLapseSize <= minToBeGone || pastLapseSize == 0) {
                    msg = "sick lapse < min to gone";
                    newState = ShardState.GONE;
                } else {
                    msg = "sick lapse > max. sick to stay online";
                    newState = ShardState.QUARANTINE;
                }
            } else if (pastLapseSize <= minToBeGone && currentState == QUARANTINE) {
                msg = "sick lapse < min to gone";
                newState = ShardState.GONE;
            } else if (pastLapseSize > 0 && currentState == ShardState.ONLINE) {
                msg = "sick lapse > 0 (" + pastLapseSize + ")";
                newState = ShardState.QUARANTINE;
            } else if (pastLapseSize == 0 && currentState == QUARANTINE) {
                msg = "sick lapse = 0 ";
                newState = ShardState.GONE;
            } else {
                msg = "lapse is wtf=" + pastLapseSize;
            }
        }
    }

    logger.info("{}: {} {} {}, {}, ({}/{}), Seq [{}..{}] {}", getClass().getSimpleName(), shard,
            newState == currentState ? "stays in" : "changing to", newState, msg, all.size(),
            pastLapse != null ? pastLapse.size() : 0, all.get(all.size() - 1).getSequenceId(),
            all.get(0).getSequenceId(), shardId.equals(shard.getShardID()) ? LogUtils.SPECIAL : "");

    return newState;
}

From source file:com.thoughtworks.go.server.service.ElasticProfileService.java

public List<ElasticProfile> findElasticAgentProfilesByPluginId(String pluginId) {
    ClusterProfiles allClusterProfiles = goConfigService.getElasticConfig().getClusterProfiles();

    return getPluginProfiles().stream().filter(
            profile -> allClusterProfiles.find(profile.getClusterProfileId()).getPluginId().equals(pluginId))
            .collect(Collectors.toCollection(ArrayList::new));
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.CommunityServiceImpl.java

@Override
public Page<UserDTO> getLeaders(Pageable pageable) {
    Page<User> users = userRepository.findAll(pageable);
    List<UserDTO> result = users.getContent().stream().map(u -> hideSensitiveInformation(new UserDTO(u)))
            .collect(Collectors.toCollection(LinkedList::new));
    return new PageImpl<>(result, pageable, users.getTotalElements());
}

From source file:org.perfcake.ScenarioExecution.java

/**
 * Prints trace information for test debugging purposes.
 *///from   ww  w .  j  a va2  s .c  om
private void printTraceInformation() {
    if (log.isTraceEnabled()) {
        log.trace("System properties:");
        final List<String> p = System.getProperties().entrySet().stream()
                .map(entry -> "\t" + entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.toCollection(() -> new LinkedList<>()));

        Collections.sort(p);

        for (final String s : p) {
            log.trace(s);
        }

        // Print classpath
        log.trace("Classpath:");
        final ClassLoader currentCL = ScenarioExecution.class.getClassLoader();
        final URL[] curls = ((URLClassLoader) currentCL).getURLs();

        for (final URL curl : curls) {
            log.trace("\t" + curl);
        }
    }
}