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.joyent.manta.client.jobs.MantaJob.java

/**
 * List of all of the map phases of the job.
 *
 * @return list of map phases/*www  .  ja va  2 s . c om*/
 */
@JsonIgnore
public List<MantaJobPhase> getMapPhases() {
    try (Stream<MantaJobPhase> stream = phases.stream().filter(p -> p.getType().equals("map"))) {
        return stream.collect(Collectors.toCollection(ArrayList::new));
    }
}

From source file:uk.trainwatch.nrod.timetable.tools.TimeTableChecker.java

/**
 * TimingLoad maps EMU types but also train class types.
 * <p>/* w ww  . ja va2s  .c  o m*/
 * Under normal use, TimingLoad will return {@link TimingLoad#UNKNOWN} for anything it doesn't know about.
 * <p>
 * So, to support new types, this shows how to scan for unsupported classes and generates the source so you can past
 * it into TimingLoad.
 * <p>
 * @throws IOException
 */
private void findUnsupportedTimingLoads(final Path cifFile) {
    // Strict mode so we fail on an invalid record type
    final CIFParser parser = new CIFParser(true);

    CounterConsumer<String> found = new CounterConsumer<>();

    LOG.log(Level.INFO, "Scanning for unsupported TimingLoad's...");

    lines(cifFile).map(parser::parse).map(Functions.castTo(BasicSchedule.class)).filter(Objects::nonNull).
    // Filter for the unkown value
            filter(s -> s.getTimingLoad() == TimingLoad.UNKNOWN).
            // Swap back the original line from the file
            map(parser::currentLine).
            // Manually extract the field
            map(l -> l.substring(53, 57)).
            // Filter so we only have valid classes
            filter(s -> s.matches("\\d\\d\\d ")).
            // Trim
            map(String::trim).
            // Count it for the result
            peek(found).
            // collect into a set then report findings
            collect(Collectors.toCollection(() -> new TreeSet())).
            // This is formatted so can be pasted into TimingLoad source
            forEach(c -> System.out.printf("/**\n/* Class %1$s\n*/\nC%1$s(\"%1$s\",\"Class %1$s\"),\n", c));

    LOG.log(Level.INFO, () -> "Found " + found.get() + " unknown entries");
}

From source file:io.github.lxgaming.teleportbow.util.Toolbox.java

@SafeVarargs
public static <E> LinkedHashSet<E> newLinkedHashSet(E... elements) {
    return Stream.of(elements).collect(Collectors.toCollection(LinkedHashSet::new));
}

From source file:delfos.dataset.basic.item.ContentDatasetDefault.java

@Override
public String toString() {
    Set<String> items = this.stream().map((item) -> "Item " + item.getId())
            .collect(Collectors.toCollection(TreeSet::new));
    return items.toString();
}

From source file:org.elasticsearch.client.CustomRestHighLevelClientTests.java

/**
 * The {@link RestHighLevelClient} must declare the following execution methods using the <code>protected</code> modifier
 * so that they can be used by subclasses to implement custom logic.
 *///from  w  w w.  j  a  va2 s .c  o  m
@SuppressForbidden(reason = "We're forced to uses Class#getDeclaredMethods() here because this test checks protected methods")
public void testMethodsVisibility() throws ClassNotFoundException {
    final String[] methodNames = new String[] { "parseEntity", "parseResponseException", "performRequest",
            "performRequestAndParseEntity", "performRequestAsync", "performRequestAsyncAndParseEntity" };

    final Set<String> protectedMethods = Arrays.stream(RestHighLevelClient.class.getDeclaredMethods())
            .filter(method -> Modifier.isProtected(method.getModifiers())).map(Method::getName)
            .collect(Collectors.toCollection(TreeSet::new));

    assertThat(protectedMethods, contains(methodNames));
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

/**
 * Converts an array of <code>InsertElementRule</code> annotations into the corresponding rewriting rules.
 * /*  w  ww .j  a  v  a2s.  c  om*/
 * @param rules
 * @return
 */
public static List<Rule> wrap(InsertElementRule[] rules) {
    Validate.notNull(rules, "rules must not be NULL");
    return Stream.of(rules).map(XMLRewrite::wrap).collect(Collectors.toCollection(ArrayList::new));
}

From source file:se.backede.jeconomix.forms.report.SingleTransactionReport.java

public void filter() {

    companyComboBox.setEnabled(false);/*from  ww  w  .ja v  a 2 s .  c  om*/
    yearComboBox.setEnabled(false);
    monthComboBox.setEnabled(false);

    LinkedList<TransactionDto> allTrasactions = new LinkedList<TransactionDto>(reports.getTransctions());

    CompanyDto company = (CompanyDto) companyComboBox.getSelectedItem();

    String yearString = (String) yearComboBox.getSelectedItem();
    Integer year = Integer.parseInt("0");
    if (yearString != null) {
        if (!yearString.equals(ALL_YEARS)) {
            year = Integer.parseInt(yearString);
        }
    }

    String monthString = (String) monthComboBox.getSelectedItem();
    Month month = null;
    if (monthString != null) {
        if (!monthString.equals(ALL_MONTHS)) {
            month = Month.valueOf(monthString);
        }
    }

    LinkedList<TransactionDto> filteredCompanies = new LinkedList<>(reports.getTransctions());

    if (company != null) {
        if (!company.getName().equals(ALL_COMPANIES)) {
            filteredCompanies = allTrasactions.stream().filter(line -> line.getCompany().equals(company))
                    .collect(Collectors.toCollection(LinkedList::new));
        }
    }

    LinkedList<TransactionDto> filteredByYear = (LinkedList) filteredCompanies.clone();
    if (yearString != null) {
        if (!yearString.equals(ALL_YEARS)) {
            for (TransactionDto filteredTransaction : filteredCompanies) {
                if (!Objects.equals(filteredTransaction.getBudgetYear(), year)) {
                    filteredByYear.remove(filteredTransaction);
                }
            }
        }
    }

    LinkedList<TransactionDto> filteredByMonth = (LinkedList) filteredByYear.clone();
    if (monthString != null) {
        if (!monthString.equals(ALL_MONTHS)) {
            for (TransactionDto filteredTransaction : filteredByYear) {
                if (filteredTransaction.getBudgetMonth() != month) {
                    filteredByMonth.remove(filteredTransaction);
                }
            }
        }
    }

    DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();

    rightRenderer.setHorizontalAlignment(JLabel.RIGHT);

    TransactionCompanyModel transModel = new TransactionCompanyModel(new HashSet<>(filteredByMonth));

    transactionTable.setModel(transModel);

    transactionTable.getColumnModel().getColumn(2).setCellRenderer(rightRenderer);

    transactionSumLabel.setText(transModel.getSum().toString().concat(" Kr"));
    categoryNameLabel.setText(reports.getCategory());

    companyComboBox.setEnabled(true);
    yearComboBox.setEnabled(true);
    monthComboBox.setEnabled(true);

}

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

@Override
public PolicyEvaluationResult evalPolicy(final PolicyEvaluationRequestV1 request) {
    ZoneEntity zone = this.zoneResolver.getZoneEntityOrFail();
    String uri = request.getResourceIdentifier();
    String subjectIdentifier = request.getSubjectIdentifier();
    String action = request.getAction();
    LinkedHashSet<String> policySetsEvaluationOrder = request.getPolicySetsEvaluationOrder();

    if (uri == null || subjectIdentifier == null || action == null) {
        LOGGER.error(String.format(
                "Policy evaluation request is missing required input parameters: "
                        + "resourceURI='%s' subjectIdentifier='%s' action='%s'",
                uri, subjectIdentifier, action));

        throw new IllegalArgumentException("Policy evaluation request is missing required input parameters. "
                + "Please review and resubmit the request.");
    }//from w  ww .  j  a  va  2s  .  c  om

    List<PolicySet> allPolicySets = this.policyService.getAllPolicySets();

    if (allPolicySets.isEmpty()) {
        return new PolicyEvaluationResult(Effect.NOT_APPLICABLE);
    }

    LinkedHashSet<PolicySet> filteredPolicySets = filterPolicySetsByPriority(subjectIdentifier, uri,
            allPolicySets, policySetsEvaluationOrder);

    // At this point empty evaluation order means we have only one policy set.
    // Fixing policy evaluation order so we could build a cache key.
    PolicyEvaluationRequestCacheKey key;
    if (policySetsEvaluationOrder.isEmpty()) {
        key = new Builder().zoneId(zone.getName())
                .policySetIds(Stream.of(filteredPolicySets.iterator().next().getName())
                        .collect(Collectors.toCollection(LinkedHashSet::new)))
                .request(request).build();
    } else {
        key = new Builder().zoneId(zone.getName()).request(request).build();
    }

    PolicyEvaluationResult result = this.cache.get(key);
    if (null == result) {
        result = new PolicyEvaluationResult(Effect.NOT_APPLICABLE);

        HashSet<Attribute> supplementalResourceAttributes;
        if (null == request.getResourceAttributes()) {
            supplementalResourceAttributes = new HashSet<>();
        } else {
            supplementalResourceAttributes = new HashSet<>(request.getResourceAttributes());
        }
        HashSet<Attribute> supplementalSubjectAttributes;
        if (null == request.getSubjectAttributes()) {
            supplementalSubjectAttributes = new HashSet<>();
        } else {
            supplementalSubjectAttributes = new HashSet<>(request.getSubjectAttributes());
        }

        for (PolicySet policySet : filteredPolicySets) {
            result = evalPolicySet(policySet, subjectIdentifier, uri, action, supplementalResourceAttributes,
                    supplementalSubjectAttributes);
            if (result.getEffect() == Effect.NOT_APPLICABLE) {
                continue;
            } else {
                break;
            }
        }

        LOGGER.info(
                String.format(
                        "Processed Policy Evaluation for: "
                                + "resourceUri='%s', subjectIdentifier='%s', action='%s'," + " result='%s'",
                        uri, subjectIdentifier, action, result.getEffect()));
        this.cache.set(key, result);
    }
    return result;
}

From source file:com.joyent.manta.client.jobs.MantaJob.java

/**
 * List of all of the reduce phases of the job.
 *
 * @return list of reduce phases//from w w w .  j a  va 2s.co m
 */
@JsonIgnore
public List<MantaJobPhase> getReducePhases() {
    try (Stream<MantaJobPhase> stream = phases.stream().filter(p -> p.getType().equals("reduce"))) {
        return stream.collect(Collectors.toCollection(ArrayList::new));
    }
}

From source file:org.codice.ddf.registry.common.metacard.RegistryUtility.java

/**
 * Attempts to return a List of Strings from an attribute. If the attribute is null the default
 * value will be returned instead./* w  w  w  .j av a2  s  .co m*/
 *
 * @param metacard - metacard to be evaluated for a List of Strings type attribute
 * @param attributeToCheck - attribute to be checked for, should be a List of Strings type
 * @return the defaultValue if attribute is not present, otherwise a List of Strings representing
 *     the values of the attribute
 */
public static List<String> getListOfStringAttribute(Metacard metacard, String attributeToCheck) {
    Attribute attribute = metacard.getAttribute(attributeToCheck);
    if (attribute == null || attribute.getValue() == null) {
        return new ArrayList<>();
    }
    return attribute.getValues().stream().map(Object::toString)
            .collect(Collectors.toCollection(ArrayList::new));
}