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:nu.yona.server.goals.service.ActivityCategoryService.java

@Cacheable(value = "activityCategorySet", key = "'instance'")
@Transactional/*from   w ww.ja  v a 2 s  . c  o m*/
public Set<ActivityCategoryDto> getAllActivityCategories() {
    // Sort the collection to make it simpler to compare the activity categories
    return StreamSupport.stream(repository.findAll().spliterator(), false)
            .map(ActivityCategoryDto::createInstance)
            .collect(Collectors
                    .toCollection(() -> new TreeSet<>((Comparator<ActivityCategoryDto> & Serializable) (l,
                            r) -> l.getName().compareTo(r.getName()))));
}

From source file:com.github.helenusdriver.driver.impl.PersistedSet.java

/**
 * Instantiates a new <code>PersistedSet</code> object.
 *
 * @author paouelle//from  www  .  j  av a 2s. c om
 *
 * @param  persisted the non-<code>null</code> persisted annotation
 * @param  persister the non-<code>null</code> persister
 * @param  fname the non-<code>null</code> field name
 * @param  set the non-<code>null</code> encoded/decoded set
 * @param  encoded <code>true</code> if the set contains encoded values;
 *         <code>false</code> if it contains decoded values (this will force
 *         all values to be encoded)
 * @throws IllegalArgumentException if unable to encode/decode the values properly
 * @throws ClassCastException if any values cannot be encoded to the expected type
 */
@SuppressWarnings("unchecked")
PersistedSet(Persisted persisted, Persister<T, PT> persister, String fname, Set<?> set, boolean encoded) {
    this.persisted = persisted;
    this.persister = persister;
    this.fname = fname;
    if (encoded) {
        this.set = ((Set<PT>) set).stream()
                .map(pt -> new PersistedValue<>(persisted, persister, fname).setEncodedValue(pt))
                .collect(Collectors.toCollection(LinkedHashSet::new)); // to preserve order
    } else {
        this.set = ((Set<T>) set).stream().map(t -> {
            final PersistedValue<T, PT> pval = new PersistedValue<>(persisted, persister, fname)
                    .setDecodedValue(t);

            pval.getEncodedValue(); // force it to be encoded
            return pval;
        }).collect(Collectors.toCollection(LinkedHashSet::new)); // to preserve order
    }
}

From source file:starnubserver.plugins.PluginManager.java

public HashSet<String> getAllLoadedPluginNames() {
    return LOADED_PLUGINS.keySet().stream().collect(Collectors.toCollection(HashSet::new));
}

From source file:org.jamocha.dn.compiler.DeepFactVariableCollector.java

private void handleChildren(final ConditionalElement<L> ce) {
    this.factVariables = ce.getChildren().stream()
            .flatMap(child -> child.accept(new DeepFactVariableCollector<>()).getFactVariables().stream())
            .collect(Collectors.toCollection(ArrayList::new));
}

From source file:net.audumla.irrigation.IrrigationZone.java

@Override
public List<Event> getIrrigationEventsForDay(Date day) {
    return irrigationEvents.stream().filter(e -> DateUtils.isSameDay(e.getEventStartTime(), day))
            .collect(Collectors.toCollection(ArrayList::new));
}

From source file:starnubserver.plugins.PluginManager.java

public HashSet<Plugin> getAllLoadedPlugins() {
    return LOADED_PLUGINS.values().stream().collect(Collectors.toCollection(HashSet::new));
}

From source file:com.bouncestorage.swiftproxy.v1.AccountResource.java

@GET
public Response getAccount(@NotNull @PathParam("account") String account,
        @QueryParam("limit") Optional<Integer> limit, @QueryParam("marker") Optional<String> marker,
        @QueryParam("end_marker") Optional<String> endMarker, @QueryParam("format") Optional<String> format,
        @QueryParam("prefix") Optional<String> prefix, @QueryParam("delimiter") Optional<String> delimiter,
        @HeaderParam("X-Auth-Token") String authToken,
        @HeaderParam("X-Newest") @DefaultValue("false") boolean newest,
        @HeaderParam("Accept") Optional<String> accept) {
    delimiter.ifPresent(x -> logger.info("delimiter not supported yet"));

    BlobStore blobStore = getBlobStore(authToken).get();
    ArrayList<ContainerEntry> entries = blobStore.list().stream().map(StorageMetadata::getName)
            .filter(name -> marker.map(m -> name.compareTo(m) > 0).orElse(true))
            .filter(name -> endMarker.map(m -> name.compareTo(m) < 0).orElse(true))
            .filter(name -> prefix.map(name::startsWith).orElse(true)).map(ContainerEntry::new)
            .collect(Collectors.toCollection(ArrayList::new));

    MediaType formatType;//w  w  w. j  a  va2  s.c o  m
    if (format.isPresent()) {
        formatType = BounceResourceConfig.getMediaType(format.get());
    } else if (accept.isPresent()) {
        formatType = MediaType.valueOf(accept.get());
    } else {
        formatType = MediaType.TEXT_PLAIN_TYPE;
    }

    if (blobStore.getContext().unwrap().getId().equals("transient")) {
        entries.sort((a, b) -> a.getName().compareTo(b.getName()));
    }

    long count = entries.size();
    limit.ifPresent((max) -> {
        if (entries.size() > max) {
            entries.subList(max, entries.size()).clear();
        }
    });

    Account root = new Account();
    root.name = account;
    root.container = entries;
    return output(root, entries, formatType).header("X-Account-Container-Count", count)
            .header("X-Account-Object-Count", -1).header("X-Account-Bytes-Used", -1).header("X-Timestamp", -1)
            .header("X-Trans-Id", -1).header("Accept-Ranges", "bytes").build();
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.LocalDiskProfileReader.java

public InputStream readArchiveProfileFrom(Path profilePath) throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();//from w w w.  ja v  a 2  s .  co  m
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:com.mycompany.wolf.Room.java

public void addPlayer(Session session) {
    synchronized (mutex) {
        sessions.add(session);// w  w w.j av a 2s .c o m
        List<Map<String, String>> roomInfo = sessions.stream()
                .map(s -> ImmutableMap.of("playerId", getPlayerId(s)))
                .collect(Collectors.toCollection(LinkedList::new));
        Map<String, Object> m = ImmutableMap.of("code", "enterResp", "properties",
                ImmutableMap.of("roomInfo", roomInfo));
        String json = new Gson().toJson(m);
        sessions.stream().forEach(s -> {
            s.getAsyncRemote().sendText(json);
        });
    }
}

From source file:org.nuxeo.enrichers.RelationDocumentsContentEnricher.java

@Override
public void write(JsonGenerator jg, DocumentModel document) throws IOException {
    Principal principal = ctx.getSession(document).getSession().getPrincipal();
    try (SessionWrapper wrapper = ctx.getSession(document)) {
        String id = document.getId();
        new UnrestrictedSessionRunner(wrapper.getSession()) {
            @Override//ww w.ja  v  a  2  s  .  co  m
            public void run() {
                // control the graph depth
                try (Closeable resource = ctx.wrap().controlDepth().open()) {
                    StringBuilder query = new StringBuilder("SELECT * FROM ");
                    query.append("DefaultRelation").append(" WHERE ").append("relation:source").append("=")
                            .append(NXQL.escapeString(id)).append(Operator.OR.toString())
                            .append(" " + "relation:target" + " ").append("=").append(NXQL.escapeString(id));
                    DocumentModelList relations = session.query(query.toString());
                    Predicate<DocumentModel> canReadSourceDocument = doc -> session.hasPermission(principal,
                            new IdRef((String) doc.getPropertyValue("relation:source")),
                            SecurityConstants.READ);
                    Predicate<DocumentModel> canReadTargetDocument = doc -> session.hasPermission(principal,
                            new IdRef((String) doc.getPropertyValue("relation:target")),
                            SecurityConstants.READ);
                    Predicate<DocumentModel> canReadRelatedDocuments = canReadSourceDocument
                            .and(canReadTargetDocument);
                    DocumentModelList accessableRelations = relations.stream().filter(canReadRelatedDocuments)
                            .collect(Collectors.toCollection(DocumentModelListImpl::new));
                    jg.writeFieldName(NAME);
                    // delegate the marshalling to Nuxeo Platform
                    writeEntity(accessableRelations, jg);
                } catch (MaxDepthReachedException e) {
                    // do not apply enricher
                } catch (IOException e) {
                    LOG.error(e, e);
                }

            }
        }.runUnrestricted();
    }

}