Example usage for java.util.stream Collectors toMap

List of usage examples for java.util.stream Collectors toMap

Introduction

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

Prototype

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) 

Source Link

Document

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Usage

From source file:com.formkiq.core.form.bean.FormFieldMapper.java

/**
 * Transform {@link FormJSON} to a Map of {@link FormJSONField}.
 * @param form {@link FormJSON}//from w w w .j a  va  2 s  . co m
 * @return {@link Map}
 */
public static Map<String, FormJSONField> transformToValueMap(final FormJSON form) {

    return form.getSections().stream().flatMap(s -> s.getFields().stream())
            .filter(f -> !isEmpty(f.getValuekey()) && !f.isHide())
            .collect(Collectors.toMap(f -> f.getValuekey(), f -> f));
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesStatefulSetCachingAgent.java

@Override
protected Map<KubernetesManifest, List<KubernetesManifest>> loadSecondaryResourceRelationships(
        List<KubernetesManifest> primaryResourceList) {
    BiFunction<String, String, String> manifestName = (namespace, name) -> namespace + ":" + name;

    Map<String, KubernetesManifest> services = namespaces.stream()
            .map(n -> credentials.list(KubernetesKind.SERVICE, n)).flatMap(Collection::stream)
            .collect(Collectors.toMap((m) -> manifestName.apply(m.getNamespace(), m.getName()), (m) -> m));

    Map<KubernetesManifest, List<KubernetesManifest>> result = new HashMap<>();

    for (KubernetesManifest manifest : primaryResourceList) {
        String serviceName = KubernetesStatefulSetHandler.serviceName(manifest);
        if (StringUtils.isEmpty(serviceName)) {
            continue;
        }/*from   ww  w  .  j a v  a 2s .co m*/

        String key = manifestName.apply(manifest.getNamespace(), serviceName);

        if (!services.containsKey(key)) {
            continue;
        }

        KubernetesManifest service = services.get(key);
        result.put(manifest, Collections.singletonList(service));
    }

    return result;
}

From source file:com.netflix.spinnaker.igor.config.TravisConfig.java

@Bean
public Map<String, TravisService> travisMasters(BuildMasters buildMasters, TravisCache travisCache,
        IgorConfigurationProperties igorConfigurationProperties, @Valid TravisProperties travisProperties,
        ObjectMapper objectMapper, ArtifactDecorator artifactDecorator) {
    log.info("creating travisMasters");

    Map<String, TravisService> travisMasters = (travisProperties == null
            ? new ArrayList<TravisProperties.TravisHost>()
            : travisProperties.getMasters()).stream().map(host -> {
                String travisName = "travis-" + host.getName();
                log.info("bootstrapping {} as {}", host.getAddress(), travisName);

                TravisClient client = travisClient(host.getAddress(),
                        igorConfigurationProperties.getClient().getTimeout(), objectMapper);
                return travisService(travisName, host.getBaseUrl(), host.getGithubToken(),
                        host.getNumberOfRepositories(), client, travisCache, artifactDecorator,
                        (travisProperties == null ? null : travisProperties.getRegexes()));
            }).collect(Collectors.toMap(TravisService::getGroupKey, Function.identity()));

    buildMasters.getMap().putAll(travisMasters);
    return travisMasters;
}

From source file:com.yahoo.bard.webservice.config.ModuleLoader.java

/**
 * Build the graph of configurations and dependencies.
 *
 * @return A graph whose vertices are Configurations and whose edges are dependencies between them.
 *
 * @throws SystemConfigException If any errors occur while parsing the configurations into a graph.
 */// www  .  j a  v a  2s.  c o  m
private ConfigurationGraph loadConfigurationGraph() throws SystemConfigException {
    try {
        Map<Configuration, String> configurationFileNameMap = configResourceLoader
                .loadResourcesWithName(MODULE_CONFIG_FILE_NAME)
                .collect(Collectors.toMap(configResourceLoader::loadConfigFromResource, Resource::getFilename));
        return new ConfigurationGraph(configurationFileNameMap, ModuleLoader::validateModuleName);

    } catch (IOException e) {
        LOG.error(MODULE_IO_EXCEPTION.logFormat(e.getMessage()));
        throw new SystemConfigException(MODULE_IO_EXCEPTION.format(e.getMessage()), e);
    }
}

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

@Override
@Nonnull/*from w w w  .  ja  va 2s .  c  o  m*/
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:com.formkiq.core.form.service.FormCalculatorServiceImpl.java

/**
 * Apply values to forms as 'formname'!id.
 * @param archive {@link ArchiveDTO}//from  w  w  w.ja  v  a 2  s.c om
 * @param values {@link Map}
 * @throws IOException IOException
 */
private void appleFieldValuesById(final ArchiveDTO archive, final Map<String, String[]> values)
        throws IOException {

    // TODO handle multiple forms with the same name.
    Map<String, FormJSON> formMap = archive.getForms().values().stream()
            .collect(Collectors.toMap(FormJSON::getName, s -> s));

    for (Map.Entry<String, String[]> e : values.entrySet()) {

        String[] split = e.getKey().split("!");

        if (split.length == 2) {

            String formname = stripQuotes(split[0]);

            int id = Integer.parseInt(split[1]);

            FormJSON form = formMap.get(formname);
            if (form != null) {

                Optional<FormJSONField> field = findField(form, id);

                if (field.isPresent()) {
                    applyValueToField(archive, form, field.get(), e.getValue());
                }
            }
        }
    }
}

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

@Nonnull
@Override/*from w  w  w.  j  a  va 2 s  .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:de.flashpixx.rrd_antlr4.generator.IBaseGenerator.java

/**
 * ctor//w  w  w. j  av  a2  s.  c  o  m
 *
 * @param p_baseoutputdirectory base output directory
 * @param p_templates array with exporting templates
 * @param p_imports set with imported grammar files
 * @param p_docuclean set with documentation strings
 */
protected IBaseGenerator(final File p_baseoutputdirectory, final Set<File> p_imports,
        final Set<String> p_docuclean, final Set<ETemplate> p_templates) {
    m_docuclean = p_docuclean;
    m_templates = p_templates;
    m_baseoutput = p_baseoutputdirectory;
    m_imports = Collections.unmodifiableMap(p_imports.parallelStream()
            .collect(Collectors.toMap(i -> FilenameUtils.removeExtension(i.getName()), i -> i)));
}

From source file:de.wpsverlinden.dupfind.FileIndexer.java

private void recAddFilesInDir(File dir) {
    try {/* ww w  . j av  a2  s  .c o  m*/
        Map<String, FileEntry> collect = Files.walk(Paths.get(dir.getCanonicalPath())).parallel()
                .filter(Files::isRegularFile).map((e) -> e.toFile()).filter((e) -> {
                    FileEntry fi = fileIndex.get(getPath(e));
                    return fi == null || fi.getLastModified() < e.lastModified();
                }).collect(Collectors.toMap((e) -> getPath(e),
                        (e) -> new FileEntry(getPath(e), e.length(), e.lastModified(), "")));
        fileIndex.putAll(collect);
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:newcontroller.handler.impl.DefaultRequest.java

@Override
public Map<String, ?> model() {
    return Collections.list(this.request.getAttributeNames()).stream()
            .collect(Collectors.toMap(Function.identity(), this.request::getAttribute));
}