Example usage for java.util Collection stream

List of usage examples for java.util Collection stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:com.github.blindpirate.gogradle.task.go.GoTest.java

private Map<File, List<File>> groupByParentDir(Collection<File> files) {
    return files.stream().collect(groupingBy(File::getParentFile));
}

From source file:org.obiba.mica.web.model.StudySummaryDtos.java

Set<String> extractCountries(Collection<Population> populations) {

    return populations.stream().filter(Population::hasModel).flatMap(p -> {
        if (p.getModel().get("selectionCriteria") instanceof Map) { //TODO: serialization should not include JsonTypeInfo to avoid this check.
            Map<String, Object> sc = (Map<String, Object>) p.getModel().get("selectionCriteria");
            List<String> countriesIso = sc.containsKey("countriesIso") ? (List<String>) sc.get("countriesIso")
                    : null;/*from   w  w  w.  j  a va  2 s. c  o m*/
            return countriesIso != null ? countriesIso.stream() : Stream.empty();
        } else {
            return Optional.ofNullable((Population.SelectionCriteria) p.getModel().get("selectionCriteria"))
                    .flatMap(sc -> Optional.ofNullable(sc.getCountriesIso().stream())).orElseGet(Stream::empty);
        }
    }).filter(Objects::nonNull).collect(toSet());
}

From source file:com.ejisto.modules.vertx.handler.ApplicationInstallerWizardHandler.java

private void handleApplicationPublish(HttpServerRequest req, MultiMap params, Buffer buffer)
        throws NotInstalledException {
    List<MockedField> newFields = JSONUtil.decode(buffer.toString(), Boilerplate.MF_LIST_TYPE_REFERENCE);
    String sessionID = params.get(SESSION_ID);
    final Optional<TemporaryWebApplicationDescriptor> optional = ApplicationInstallerRegistry
            .getDescriptor(sessionID).map(TemporaryWebApplicationDescriptor.class::cast);
    if (!optional.isPresent()) {
        writeError(req, HttpResponseStatus.BAD_REQUEST.code(), "invalid sessionID");
        return;/*from   w  w  w .  ja  v  a  2  s.  c  o  m*/
    }
    TemporaryWebApplicationDescriptor temporaryDescriptor = optional.get();
    final Collection<MockedField> descriptorFields = temporaryDescriptor.getFields();
    newFields.forEach(field -> descriptorFields.stream()
            .filter(f -> f.getComparisonKey().equals(field.getComparisonKey())).findFirst().ifPresent(f -> {
                f.setActive(true);
                f.setFieldValue(field.getFieldValue());
                f.setExpression(field.getExpression());
            }));
    final WebApplicationDescriptor descriptor = WebApplicationDescriptor.copyOf(temporaryDescriptor);
    descriptorFields.stream().forEach(f -> f.setContextPath(descriptor.getContextPath()));
    mockedFieldsRepository.deleteContext(descriptor.getContextPath());
    mockedFieldsRepository.insert(descriptorFields);
    webApplicationDescriptorDao.insert(descriptor);
    ClassPool classPool = ClassPoolRepository.getRegisteredClassPool(temporaryDescriptor.getContextPath());
    ClassPoolRepository.replaceClassPool(descriptor.getContextPath(), classPool);
    String containerID = Optional.ofNullable(descriptor.getContainerId())
            .orElse(StringConstants.DEFAULT_CONTAINER_ID.getValue());
    eventManager.publishEvent(new ApplicationInstallFinalization(this, descriptor,
            containersRepository.loadContainer(containerID)));
    req.response().setStatusCode(HttpResponseStatus.OK.code()).end();
}

From source file:mtsar.processors.answer.KOSAggregator.java

@Override
@Nonnull/*from w  ww .  j a  v a2s  .c  om*/
public Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks) {
    requireNonNull(stage, "the stage provider should not provide null");
    checkArgument(tasks.stream().allMatch(SINGLE_BINARY_TYPE),
            "tasks should be of the type single and have only two possible answers");
    if (tasks.isEmpty())
        return Collections.emptyMap();

    final List<Answer> answers = answerDAO.listForStage(stage.getId());
    if (answers.isEmpty())
        return Collections.emptyMap();

    final Map<Integer, Task> taskMap = taskDAO.listForStage(stage.getId()).stream().filter(SINGLE_BINARY_TYPE)
            .collect(Collectors.toMap(Task::getId, Function.identity()));

    final Map<Integer, BiMap<String, Short>> answerIndex = taskMap.values().stream()
            .collect(Collectors.toMap(Task::getId, task -> {
                final BiMap<String, Short> map = HashBiMap.create(2);
                map.put(task.getAnswers().get(0), (short) -1);
                map.put(task.getAnswers().get(1), (short) +1);
                return map;
            }));

    /* rows are tasks IDs, columns are worker IDs, values are answers */
    final Table<Integer, Integer, Short> graph = HashBasedTable.create();

    for (final Answer answer : answers) {
        if (!answer.getType().equalsIgnoreCase(AnswerDAO.ANSWER_TYPE_ANSWER))
            continue;
        graph.put(answer.getTaskId(), answer.getWorkerId(),
                answerIndex.get(answer.getTaskId()).get(answer.getAnswers().get(0)));
    }

    final Map<Integer, Double> estimations = converge(graph, getKMax());
    return estimations.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, estimation -> {
        final String answer = answerIndex.get(estimation.getKey()).inverse()
                .get(estimation.getValue() < 0 ? (short) -1 : (short) +1);
        return new AnswerAggregation.Builder().setTask(taskMap.get(estimation.getKey())).addAnswers(answer)
                .build();
    }));
}

From source file:mtsar.processors.meta.ZenCrowd.java

@Nonnull
@Override//ww w  .  j  a v a 2s .  c o m
public Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers) {
    requireNonNull(stage, "the stage provider should not provide null");
    if (workers.isEmpty())
        return Collections.emptyMap();
    final Map<Integer, Worker> workerIds = workers.stream()
            .collect(Collectors.toMap(Worker::getId, Function.identity()));
    final Models.ZenModel<Integer, Integer, String> zenModel = compute(stage, answerDAO, getTaskMap())
            .getZenModel();
    final ZenCrowdEM<Integer, Integer, String> zenCrowd = new ZenCrowdEM<>(zenModel);
    zenCrowd.computeLabelEstimates();
    try {
        @SuppressWarnings("unchecked")
        final Map<Integer, Double> reliability = (Map<Integer, Double>) FieldUtils.readField(zenCrowd,
                "workerReliabilityMap", true);
        final Map<Integer, WorkerRanking> rankings = reliability.entrySet().stream()
                .filter(entry -> workerIds.containsKey(entry.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> new WorkerRanking.Builder()
                        .setWorker(workerIds.get(entry.getKey())).setReputation(entry.getValue()).build()));
        return rankings;
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.epam.ta.reportportal.ws.controller.impl.ProjectControllerTest.java

@Test
public void getAllProjectsInfo() throws Exception {
    final MvcResult mvcResult = mvcMock.perform(get(
            "/project/list?page.page=1&page.size=51&page.sort=name,DESC&filter.eq.configuration$entryType=INTERNAL")
                    .principal(authentication()))
            .andExpect(status().is(200)).andReturn();
    Page<ProjectInfoResource> entries = objectMapper.readValue(mvcResult.getResponse().getContentAsString(),
            new TypeReference<Page<ProjectInfoResource>>() {
            });//w  w w .jav  a2  s.com
    final Collection<ProjectInfoResource> content = entries.getContent();
    assertThat(content).hasSize(2);
    assertThat(content.stream().map(ProjectInfoResource::getProjectId).collect(Collectors.toList()))
            .containsSequence("project2", "project1");
    content.stream().forEach(it -> assertThat(it.getEntryType()).isEqualTo("INTERNAL"));
}

From source file:nu.yona.server.messaging.service.MessageService.java

private void deleteMessages(Collection<Message> messages) {
    Set<Message> messagesToBeDeleted = messages.stream()
            .flatMap(m -> m.getMessagesToBeCascadinglyDeleted().stream()).collect(Collectors.toSet());
    messagesToBeDeleted.addAll(messages);
    Set<MessageDestination> involvedMessageDestinations = messagesToBeDeleted.stream()
            .map(Message::getMessageDestination).collect(Collectors.toSet());

    messagesToBeDeleted.forEach(Message::prepareForDelete);
    involvedMessageDestinations.forEach(d -> MessageDestination.getRepository().saveAndFlush(d));

    messagesToBeDeleted.forEach(m -> m.getMessageDestination().remove(m));
    involvedMessageDestinations.forEach(d -> MessageDestination.getRepository().save(d));
}

From source file:simx.profiler.info.application.MessagesInfoTopComponent.java

@Override
public void resultChanged(LookupEvent le) {
    Collection<? extends CommunicationData> allSelectedTypes = result.allInstances();
    if (!allSelectedTypes.isEmpty()) {
        allSelectedTypes.stream().forEach((type) -> {
            this.setData(type);
        });/*  w w  w .  ja v a  2s .  c om*/
    } else {
        System.out.println("No selection");
    }
}

From source file:uk.dsxt.voting.client.ClientManager.java

public RequestResult getAllVoteStatuses(String votingId) {
    List<VoteStatusWeb> results = new ArrayList<>();
    final Collection<VoteStatus> votes = assetsHolder.getVoteStatuses(votingId);
    results.addAll(votes.stream().map(VoteStatusWeb::new).collect(Collectors.toList()));
    return new RequestResult<>(results.toArray(new VoteStatusWeb[results.size()]), null);
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Calls user merge on the various possibly duplicate elements, and sorts out user responses
 * @param tx//from  w  w w. j  a  va 2s  .  com
 * @param config
 * @param security_service
 * @param logger
 * @param maybe_merger
 * @param titan_mapper
 * @param element_type
 * @param key
 * @param new_elements
 * @param existing_elements
 * @return
 */
protected static <O extends Element> List<O> invokeUserMergeCode(final TitanTransaction tx,
        final GraphSchemaBean config, final Tuple2<String, ISecurityService> security_service,
        final Optional<IBucketLogger> logger,
        final Optional<Tuple2<IEnrichmentBatchModule, GraphMergeEnrichmentContext>> maybe_merger,
        final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper,
        final MutableStatsBean mutable_stats, final Class<O> element_type, final String bucket_path,
        final ObjectNode key, final Collection<ObjectNode> new_elements, final Collection<O> existing_elements,
        final Map<ObjectNode, Vertex> mutable_existing_vertex_store) {
    if (existing_elements.isEmpty() && (1 == new_elements.size()) && !config.custom_finalize_all_objects()) {

        return validateUserElement(new_elements.stream().findFirst().get(), config)
                .bind(el -> addGraphSON2Graph(bucket_path, key, el, mutable_existing_vertex_store,
                        Collections.emptyMap(), tx, element_type, mutable_stats))
                .<List<O>>validation(fail -> {
                    if (Vertex.class.isAssignableFrom(element_type))
                        mutable_stats.vertex_errors++;
                    else if (Edge.class.isAssignableFrom(element_type))
                        mutable_stats.edge_errors++;

                    logger.ifPresent(l -> l.inefficientLog(Level.DEBUG,
                            BeanTemplateUtils.clone(fail)
                                    .with(BasicMessageBean::source, "GraphBuilderEnrichmentService")
                                    .with(BasicMessageBean::command, "system.onObjectBatch").done()));
                    //(keep this here for c/p purposes .. if want to attach an expensive "details" object then could do that by copying the fields across one by one)                        
                    //                        logger.ifPresent(l -> l.log(Level.DEBUG,                        
                    //                              ErrorUtils.lazyBuildMessage(true, () -> "GraphBuilderEnrichmentService", 
                    //                                    () -> "system.onObjectBatch", 
                    //                                    () -> null, 
                    //                                    () -> ErrorUtils.get("MESSAGE", params),
                    //                                    () -> null)
                    //                                    ));                  

                    return Collections.emptyList();
                }, success -> Arrays.<O>asList(success));
    } else {
        // (just gives me the elements indexed by their ids so we can get them back again later)
        // (we'll convert to string as a slightly inefficient way of ensuring the same code can handle both edge andv vertex cases)
        final Map<String, Optional<O>> mutable_existing_element_vs_id_store = existing_elements.stream()
                .collect(Collectors.toMap(e -> e.id().toString(), e -> Optional.of(e)));

        return maybe_merger.<List<O>>map(merger -> {

            final Stream<Tuple2<Long, IBatchRecord>> in_stream = Stream.concat(
                    new_elements.stream().map(j -> Tuples._2T(0L, new BatchRecordUtils.JsonBatchRecord(j))),
                    existing_elements.stream().sorted((a, b) -> ((Long) a.id()).compareTo((Long) b.id())) // (ensure first found element has the lowest id)
                            .map(v -> _mapper.convertValue(titan_mapper.convertValue(v, Map.class),
                                    JsonNode.class))
                            .map(j -> Tuples._2T(0L, new BatchRecordUtils.InjectedJsonBatchRecord(j))));

            merger._2().initializeMerge(element_type);

            merger._1().onObjectBatch(in_stream, Optional.of(new_elements.size()), Optional.of(key));

            return merger._2().getAndResetElementList().stream()
                    .map(o -> addGraphSON2Graph(bucket_path, key, o, mutable_existing_vertex_store,
                            mutable_existing_element_vs_id_store, tx, element_type, mutable_stats))
                    .<O>flatMap(v -> v.validation(fail -> {
                        if (Vertex.class.isAssignableFrom(element_type))
                            mutable_stats.vertex_errors++;
                        else if (Edge.class.isAssignableFrom(element_type))
                            mutable_stats.edge_errors++;

                        logger.ifPresent(l -> l.inefficientLog(Level.DEBUG,
                                BeanTemplateUtils.clone(fail)
                                        .with(BasicMessageBean::source, "GraphBuilderEnrichmentService")
                                        .with(BasicMessageBean::command, "system.onObjectBatch").done()));

                        return Stream.empty();
                    }, success -> Stream.of(success))).collect(Collectors.toList());
        }).orElse(Collections.emptyList());
    }
}