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:cd.go.contrib.elasticagents.dockerswarm.elasticagent.DockerSecrets.java

public List<SecretBind> toSecretBind(List<Secret> secrets) {
    final Map<String, Secret> secretMap = secrets.stream()
            .collect(Collectors.toMap(o -> o.secretSpec().name(), o -> o));
    final List<SecretBind> secretBinds = new ArrayList<>();

    for (DockerSecret dockerSecret : this) {
        final Secret secret = secretMap.get(dockerSecret.src);

        if (secret == null) {
            throw new RuntimeException(format("Secret with name `{0}` does not exist.", dockerSecret.name()));
        }//from  www  .  j  a va2 s.  com

        LOG.debug(format("Using secret `{0}` with id `{1}`.", dockerSecret.name(), secret.id()));
        final SecretFile secretFile = SecretFile.builder().name(dockerSecret.file()).uid(dockerSecret.uid())
                .gid(dockerSecret.gid()).mode(dockerSecret.mode()).build();

        secretBinds.add(SecretBind.builder().secretId(secret.id()).secretName(dockerSecret.name())
                .file(secretFile).build());
    }

    return secretBinds;
}

From source file:com.github.xdcrafts.flower.spring.impl.MiddlewareDefinition.java

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    final Map<String, List<Middleware>> groupedInjections = this.rawDefinition.entrySet().stream()
            .flatMap(e -> {//from   w  w  w  . j a  va 2 s . c om
                final List<Middleware> middleware = split(e.getValue()).stream()
                        .map(name -> applicationContext.getBean(name, Middleware.class))
                        .collect(Collectors.toList());
                return split(e.getKey()).stream().map(name -> new AbstractMap.SimpleEntry<>(name, middleware));
            }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    this.definition = namespace == null || namespace.isEmpty() ? groupedInjections
            : groupedInjections.entrySet().stream()
                    .map(e -> new AbstractMap.SimpleEntry<>(namespace + "." + e.getKey(), e.getValue()))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

From source file:edu.washington.gs.skyline.model.quantification.QuantificationTest.java

public void testNoNormalization() throws Exception {
    List<InputRecord> allInputRecords = readInputRecords("NoNormalizationInput.csv");
    allInputRecords = filterRecords(NormalizationMethod.NONE, allInputRecords);
    Map<RecordKey, Double> expected = readExpectedRows("NoNormalizationExpected.csv");
    for (Map.Entry<RecordKey, Double> entry : expected.entrySet()) {
        List<InputRecord> peptideRecords = allInputRecords.stream()
                .filter(record -> record.getRecordKey().getPeptideKey().equals(entry.getKey().getPeptideKey()))
                .collect(Collectors.toList());
        TransitionKeys allTransitionKeys = TransitionKeys
                .of(peptideRecords.stream().map(InputRecord::getTransitionKey).collect(Collectors.toSet()));
        List<InputRecord> replicateRecords = allInputRecords.stream()
                .filter(record -> record.getRecordKey().equals(entry.getKey())).collect(Collectors.toList());
        Map<String, Double> areaMap = replicateRecords.stream()
                .collect(Collectors.toMap(InputRecord::getTransitionKey, InputRecord::getArea));
        TransitionAreas transitionAreas = TransitionAreas.fromMap(areaMap);
        assertCloseEnough(entry.getValue(), transitionAreas.totalArea(allTransitionKeys));
    }/*from w  w w .  ja  v a2s .  com*/
}

From source file:com.netflix.spinnaker.fiat.roles.file.FileBasedUserRolesProvider.java

@Override
public Map<String, Collection<Role>> multiLoadRoles(Collection<String> userIds) {
    try {/*w ww .  j a  va  2 s. co  m*/
        return parse().entrySet().stream().filter(e -> userIds.contains(e.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    } catch (IOException io) {
        log.error("Couldn't mulitLoad roles from file", io);
    }
    return Collections.emptyMap();
}

From source file:nu.yona.server.goals.service.ActivityCategoryDto.java

private static Map<String, String> mapToStringMap(Map<Locale, String> localeMap) {
    return localeMap.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey().toLanguageTag(), Map.Entry::getValue));
}

From source file:org.trustedanalytics.ingestion.kafka2hdfs.config.KafkaConfiguration.java

@Bean
public Map<String, KafkaStream<byte[], byte[]>> kafkaStreams(ConsumerConnector consumer) {
    Map<String, Integer> topicsCountMap = trackedTopics().stream()
            .collect(Collectors.toMap(topic -> topic, topic -> 1));
    Map<String, List<KafkaStream<byte[], byte[]>>> kafkaStreams = consumer.createMessageStreams(topicsCountMap);
    return kafkaStreams.keySet().stream()
            .collect(Collectors.toMap(topic -> topic, topic -> kafkaStreams.get(topic).get(0)));
}

From source file:com.ethercamp.harmony.service.JsonRpcUsageService.java

private void init(int port) {
    final String serverUrl = "http://localhost:" + port + AppConst.JSON_RPC_PATH;

    /**//from  ww w.ja  va 2 s  .com
     * Load conf file with curl examples per each JSON-RPC method.
     */
    Config config = ConfigFactory.load("json-rpc-help");
    if (config.hasPath("doc.curlExamples")) {

        Map<String, String> curlExamples = config.getAnyRefList("doc.curlExamples").stream()
                .map(e -> (HashMap<String, String>) e).collect(Collectors.toMap(e -> e.get("method"),
                        e -> e.get("curl").replace("${host}", serverUrl)));

        /**
         * Initialize empty stats for all methods.
         */
        Arrays.stream(jsonRpc.ethj_listAvailableMethods()).forEach(line -> {
            final String methodName = line.split(" ")[0];
            String curlExample = curlExamples.get(methodName);
            if (curlExample == null) {
                curlExample = generateCurlExample(line) + " " + serverUrl;
                //                            log.debug("Generate curl example for JSON-RPC method: " + methodName);
            }
            stats.put(methodName, new CallStats(methodName, 0l, null, curlExample));
        });
    }
}

From source file:com.epam.ta.reportportal.core.dashboard.impl.DeleteDashboardHandler.java

@Override
public OperationCompletionRS deleteDashboard(String dashboardId, String userName, String projectName) {

    Dashboard dashboard = dashboardRepository.findOne(dashboardId);

    BusinessRule.expect(dashboard, Predicates.notNull()).verify(ErrorType.DASHBOARD_NOT_FOUND, dashboardId);

    final List<Project> userProjects = projectRepository.findUserProjects(userName);
    Map<String, ProjectRole> roles = userProjects.stream()
            .collect(Collectors.toMap(Project::getName, p -> p.getUsers().get(userName).getProjectRole()));

    AclUtils.isAllowedToEdit(dashboard.getAcl(), userName, roles, dashboard.getName());

    BusinessRule.expect(dashboard.getProjectName(), Predicates.equalTo(projectName))
            .verify(ErrorType.ACCESS_DENIED);

    try {/*  w w w .j  a  va2 s .c o m*/
        dashboardRepository.delete(dashboardId);
    } catch (Exception e) {
        throw new ReportPortalException("Error during deleting dashboard item", e);
    }
    OperationCompletionRS response = new OperationCompletionRS();
    StringBuilder msg = new StringBuilder("Dashboard with ID = '");
    msg.append(dashboardId);
    msg.append("' successfully deleted.");
    response.setResultMessage(msg.toString());

    return response;
}

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

/**
 * Transform {@link FormJSON} to a Map of {@link FormJSONField}.
 * @param form {@link FormJSON}//  w  w  w.  j  a  va 2 s .  c  om
 * @return {@link Map}
 */
public static Map<String, FormJSONField> transformToIdMap(final FormJSON form) {
    return form.getSections().stream().flatMap(s -> s.getFields().stream())
            .collect(Collectors.toMap(f -> "" + f.getId(), f -> f));
}

From source file:com.adobe.acs.commons.data.Spreadsheet.java

/**
 * Simple constructor used for unit testing purposes
 *
 * @param convertHeaderNames If true, header names are converted
 * @param headerArray List of strings for header columns
 *///from ww w  .  j  a  v a2 s .  c  o  m
public Spreadsheet(boolean convertHeaderNames, String... headerArray) {
    this.enableHeaderNameConversion = convertHeaderNames;
    headerTypes = Arrays.stream(headerArray)
            .collect(Collectors.toMap(this::convertHeaderName, this::detectTypeFromName));
    headerRow = Arrays.asList(headerArray);
    requiredColumns = Collections.EMPTY_LIST;
    dataRows = new ArrayList<>();
    delimiters = new HashMap<>();
}