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.pmmlite.core.PmmUtils.java

public static Set<String> getConditions(Collection<TimeSeries> data) {
    return data.stream().map(s -> s.getConditions()).flatMap(List::stream).map(c -> c.getName())
            .collect(Collectors.toCollection(LinkedHashSet::new));
}

From source file:fi.hsl.parkandride.back.UtilizationDao.java

@Transactional(readOnly = true, isolation = READ_COMMITTED, propagation = MANDATORY)
@Override/*from w  w w  .j  a va2s . c o  m*/
public List<Utilization> findUtilizationsWithResolution(UtilizationKey utilizationKey, DateTime start,
        DateTime end, Minutes resolution) {
    ArrayList<Utilization> results = new ArrayList<>();
    Optional<Utilization> first = findUtilizationAtInstant(utilizationKey, start);
    try (CloseableIterator<Utilization> rest = findUtilizationsBetween(utilizationKey, start, end)) {
        LinkedList<Utilization> utilizations = Stream
                .concat(StreamUtil.asStream(first), StreamUtil.asStream(rest))
                .collect(Collectors.toCollection(LinkedList::new));

        Utilization current = null;
        for (DateTime instant = start; !instant.isAfter(end); instant = instant.plus(resolution)) {
            while (!utilizations.isEmpty() && !utilizations.getFirst().timestamp.isAfter(instant)) {
                current = utilizations.removeFirst();
            }
            if (current != null) {
                current.timestamp = instant;
                results.add(current.copy());
            }
        }
    }
    return results;
}

From source file:org.codice.ddf.registry.federationadmin.service.impl.RegistryPublicationServiceImpl.java

@Override
public void update(Metacard metacard) throws FederationAdminException {

    List<String> publishedLocations = RegistryUtility.getListOfStringAttribute(metacard,
            RegistryObjectMetacardType.PUBLISHED_LOCATIONS);

    if (publishedLocations.isEmpty()) {
        return;/* w ww .j av  a  2s.c o  m*/
    }

    Set<String> locations = publishedLocations.stream().map(registryId -> getSourceIdFromRegistryId(registryId))
            .filter(Objects::nonNull).collect(Collectors.toCollection(HashSet::new));

    if (CollectionUtils.isNotEmpty(locations)) {
        try {
            LOGGER.info("Updating publication for registry entry {}:{} at {}", metacard.getTitle(),
                    RegistryUtility.getRegistryId(metacard), String.join(",", locations));
            federationAdminService.updateRegistryEntry(metacard, locations);
        } catch (FederationAdminException e) {
            // This should not happen often but could occur if the remote registry removed the metacard
            // that was to be updated. In that case performing an add will fix the problem. If the
            // failure
            // was for another reason like the site couldn't be contacted then the add will fail
            // also and the end result will be the same.
            federationAdminService.addRegistryEntry(metacard, locations);
        }
        metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.LAST_PUBLISHED,
                Date.from(ZonedDateTime.now().toInstant())));
        federationAdminService.updateRegistryEntry(metacard);
    }
}

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

public static List<HighlightCondition> createCategorialHighlighting(Collection<? extends Element> elements,
        String property) {//w w w  .  j  a v a2s  .com
    Set<Object> categories = elements.stream().map(e -> e.getProperties().get(property))
            .filter(Objects::nonNull).collect(Collectors.toCollection(LinkedHashSet::new));
    List<HighlightCondition> conditions = new ArrayList<>();
    int index = 0;

    for (Object category : KnimeUtils.ORDERING.sortedCopy(categories)) {
        Color color = COLORS[index++ % COLORS.length];
        LogicalHighlightCondition condition = new LogicalHighlightCondition(property,
                LogicalHighlightCondition.Type.EQUAL, category.toString());

        conditions.add(new AndOrHighlightCondition(condition, property + " = " + category, true, color, false,
                false, null, null));
    }

    return conditions;
}

From source file:com.olacabs.fabric.compute.builder.impl.JarScanner.java

private List<ScanResult> scanForProcessors(ClassLoader classLoader, URL[] downloadedUrls) throws Exception {
    Reflections reflections = new Reflections(new ConfigurationBuilder().addClassLoader(classLoader)
            .addScanners(new SubTypesScanner(), new TypeAnnotationsScanner()).addUrls(downloadedUrls));
    Set<Class<?>> processors = Sets.intersection(reflections.getTypesAnnotatedWith(Processor.class),
            reflections.getSubTypesOf(ProcessorBase.class));

    return processors.stream().map(processor -> {
        Processor processorInfo = processor.getAnnotation(Processor.class);
        ComponentMetadata metadata = ComponentMetadata.builder().type(ComponentType.PROCESSOR)
                .namespace(processorInfo.namespace()).name(processorInfo.name())
                .version(processorInfo.version()).description(processorInfo.description())
                .cpu(processorInfo.cpu()).memory(processorInfo.memory())
                .processorType(processorInfo.processorType())
                .requiredProperties(ImmutableList.copyOf(processorInfo.requiredProperties()))
                .optionalProperties(ImmutableList.copyOf(processorInfo.optionalProperties())).build();

        return ScanResult.builder().metadata(metadata).componentClass(processor).build();
    }).collect(Collectors.toCollection(ArrayList::new));
}

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

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

From source file:mesclasses.handlers.ModelHandler.java

/**
 * utilis par l'emploi du temps//from   w ww .ja v a  2 s  .  co  m
 *
 * @param day
 * @return
 */
public ObservableList<Cours> getCoursForDay(String day) {
    return data.getCours().stream().filter(c -> c.getDay().equalsIgnoreCase(day))
            .collect(Collectors.toCollection(FXCollections::observableArrayList));
}

From source file:de.bund.bfr.knime.pmmlite.core.PmmUtils.java

public static Set<String> getParameters(Collection<? extends Model> models) {
    return models.stream().map(m -> m.getParamValues().keySet()).flatMap(Set::stream)
            .collect(Collectors.toCollection(LinkedHashSet::new));
}

From source file:com.epam.catgenome.manager.reference.CytobandManager.java

/**
 * Parses, validates and saves cytobands pointing to a particular reference genome. The
 * cytological cards will be separated between chromosomes.
 *
 * @param referenceId {@code Long} specifies genome ID that should be pointed to the given
 *                    cytobands/*from  w  w w  .j  av a2s.co m*/
 * @param file        {@code File} represents a reference on a file that provides cytobands
 * @throws IOException              will be thrown if any I/O errors occur
 * @throws IllegalArgumentException will be thrown in cases when a given file isn't well-formed or
 *                                  there is at least one band that doesn't provide mandatory values
 */
public void saveCytobands(final Long referenceId, final File file) throws IOException {
    boolean succeeded = false;
    final List<File> cytobandsFiles = new LinkedList<>();
    try {
        // prepares data about corresponded reference genome and parses cytobands, if
        // the given resource is available
        Assert.isTrue(file != null && file.exists(), getMessage(RESOURCE_NOT_FOUND));
        final Reference reference = referenceGenomeManager.loadReferenceGenome(referenceId);
        // collects names of all chromosomes to force cytobands validation
        final HashSet<String> dictionary = reference.getChromosomes().stream().map(Chromosome::getName)
                .collect(Collectors.toCollection(HashSet::new));
        final CytobandReader reader = CytobandReader.getInstance(file, dictionary);

        // saves cytobands in the system relatively to corresponded chromosomes
        for (final Chromosome chromosome : reference.getChromosomes()) {
            final CytobandRecord record = reader.getRecord(chromosome.getName());
            processCytobandRecord(cytobandsFiles, chromosome, record);

        }
        // sets this flag to 'true' that means all activities are performed successfully and no
        // rollback for applied changes are required
        succeeded = true;
    } finally {
        // reverts all changes that have been made in the file system, if something was going wrong
        // and we cannot create a genome in the system)
        if (!succeeded) {
            cytobandsFiles.forEach(FileUtils::deleteQuietly);
        }
        // removes an original temporary file that provides data for cytobands
        FileUtils.deleteQuietly(file);
    }
}

From source file:com.megahardcore.service.config.MultiWorldConfig.java

/**
 * Return all world names were MHC is activated
 *
 * @return world names//  w ww .ja v a2 s  .c  om
 */
public String[] getEnabledWorlds() {
    ArrayList<String> worlds = OPTIONS.rowMap().entrySet().stream().map(Map.Entry::getKey)
            .collect(Collectors.toCollection(ArrayList::new));
    return worlds.toArray(new String[worlds.size()]);
}