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.cognifide.qa.bb.aem.touch.siteadmin.aem62.SiteadminPage.java

private void goForwardToDestination(String currentUrl, String destination) {
    ChildPageRow closestPage = getChildPageWindow().getChildPageRows().stream()
            .filter(childPage -> childPage.getHref().equals(destination)).findFirst()
            .orElseGet(() -> getChildPageWindow().getChildPageRows().stream()
                    .collect(Collectors.toMap(Function.identity(),
                            childPageRow -> StringUtils.difference(currentUrl, childPageRow.getHref())))
                    .entrySet().stream().min(Comparator.comparingInt(a -> a.getValue().length())).get()
                    .getKey());//from w  w w .j  av a  2  s.  com
    closestPage.click();
}

From source file:com.derpgroup.echodebugger.resource.EchoDebuggerResource.java

@Path("/users/{userId}/intents")
@GET/*  w  w w  . j  a  va 2s .c o m*/
public Map<String, Object> getResponsesForUser(@PathParam("userId") String userId) {
    User user = (userDao.getUserById(userId) != null) ? userDao.getUserById(userId)
            : userDao.getUserByEchoId(userId);
    if (user == null) {
        EchoDebuggerLogger.logAccessRequest(userId, "ALL_INTENTS", false); // TODO: Upgrade this
        throw new ResponderException("There is no user with the id of (" + userId + ")",
                ExceptionType.UNRECOGNIZED_ID);
    }

    // TODO: Build a presentation-layer version of this object instead of returning the actual object
    return user.getIntents().entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()));
}

From source file:com.codelanx.codelanxlib.inventory.iinterface.InventoryInterface.java

/**
 * Saves an {@link InventoryInterface} to a specified {@link File} in YAML
 * /*from w  ww . j  a  v  a  2s . com*/
 * @since 0.0.1
 * @version 0.1.0
 * 
 * @param ii The {@link InventoryInterface} to save
 * @param save The {@link File} to save to
 * @throws IOException If the method failed to save to the file
 */
public static void serialize(InventoryInterface ii, File save) throws IOException {
    Validate.notNull(save, "File cannot be null");
    FileConfiguration f = YamlConfiguration.loadConfiguration(save);
    f.set("panels", ii.panels.values().stream()
            .collect(Collectors.toMap(InventoryPanel::getSerializedName, Function.identity())));
    f.save(save);
}

From source file:io.pivotal.github.GithubClient.java

public void createIssues(List<JiraIssue> issues) throws IOException, InterruptedException {
    MilestoneService milestones = new MilestoneService(client());
    Map<String, Milestone> nameToMilestone = milestones.getMilestones(createRepositoryId(), "all").stream()
            .collect(Collectors.toMap(Milestone::getTitle, Function.identity()));

    Map<String, ImportedIssue> jiraIdToImportedIssue = new HashMap<>();
    int i = 0;/*w ww  . j a v a  2s.  c om*/
    for (JiraIssue issue : issues) {
        i++;
        ImportedIssue importedIssue = importIssue(nameToMilestone, issue);
        if (i % 100 == 0) {
            System.out.println("Migrated " + i + " issues");
        }
        jiraIdToImportedIssue.put(issue.getKey(), importedIssue);
    }
    System.out.println("Migrated " + i + " issues total");

    System.out.println("Creating backported issues");
    int b = 0;
    for (ImportedIssue importedIssue : jiraIdToImportedIssue.values()) {
        if (importedIssue.getBackportVersions().isEmpty()) {
            continue;
        }
        createBackports(nameToMilestone, importedIssue);
        b += importedIssue.getBackportVersions().size();
        if (b % 100 == 0) {
            System.out.println("Backported " + b + " issues");
        }
    }
    System.out.println("Backported " + b + " issues total");

    IssueService issueService = new IssueService(client());
    for (ImportedIssue importedIssue : jiraIdToImportedIssue.values()) {
        int issueNumber = getImportedIssueNumber(importedIssue);
        List<IssueLink> outwardIssueLinks = importedIssue.getJiraIssue().getFields().getIssuelinks().stream()
                .filter(l -> l.getOutwardIssue() != null).collect(Collectors.toList());
        if (outwardIssueLinks.isEmpty()) {
            continue;
        }
        String comment = "\n";
        for (IssueLink outward : outwardIssueLinks) {
            String linkedJiraKey = outward.getOutwardIssue().getKey();
            // might be null if linked to a JIRA that was not queried (i.e. we migrate Spring Security and it relates to Spring Framework)
            ImportedIssue linkedIssue = jiraIdToImportedIssue.get(linkedJiraKey);
            String linkedIssueReference = linkedIssue == null
                    ? JiraIssue.getBrowserUrl(jiraConfig.getBaseUrl(), linkedJiraKey)
                    : getImportedIssueReference(linkedIssue);
            comment += "\nThis issue " + outward.getType().getOutward() + " " + linkedIssueReference;
        }
        issueService.createComment(createRepositoryId(), issueNumber, comment);
    }

}

From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBeanTest.java

public void testGetModifyXslExport() throws AccessDeniedException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = new AdminUser();
    user.setRoles(/*  www.  j a  va 2  s . c  o m*/
            AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity())));
    Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);
    request.setParameter("id_xsl_export", Integer.toString(_xslExport.getIdXslExport()));
    _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);
    assertNotNull(_instance.getModifyXslExport(request));
}

From source file:org.ligoj.app.plugin.prov.aws.in.ProvAwsPriceImportResource.java

/**
 * Install compute prices from the JSON file provided by AWS.
 *
 * @param context/*from w w  w.  jav a  2s . c om*/
 *            The update context.
 */
private void installComputePrices(final UpdateContext context) throws IOException {
    // Create the Spot instance price type
    final Node node = context.getNode();
    final ProvInstancePriceTerm spotPriceType = newSpotInstanceType(node);
    context.setPriceTypes(iptRepository.findAllBy(BY_NODE, node.getId()).stream()
            .collect(Collectors.toMap(ProvInstancePriceTerm::getCode, Function.identity())));

    // The previously installed instance types cache. Key is the instance name
    context.setInstanceTypes(itRepository.findAllBy(BY_NODE, node.getId()).stream()
            .collect(Collectors.toMap(ProvInstanceType::getName, Function.identity())));

    installPrices(context, "ec2", configuration.get(CONF_URL_EC2_PRICES_SPOT, EC2_PRICES_SPOT),
            SpotPrices.class, (r, region) -> {
                // Get previous prices for this location
                context.setPrevious(ipRepository.findAll(node.getId(), region.getName()).stream()
                        .collect(Collectors.toMap(ProvInstancePrice::getCode, Function.identity())));

                // Install the EC2 prices and related instance details used later
                final int ec2Prices = installEC2Prices(context, region);
                nextStep(node, region.getName(), 1);

                // Install the SPOT EC2 prices
                return ec2Prices
                        + r.getInstanceTypes().stream().flatMap(t -> t.getSizes().stream()).filter(j -> {
                            final boolean availability = context.getInstanceTypes().containsKey(j.getName());
                            if (!availability) {
                                // Unavailable instances type of spot are ignored
                                log.warn("Instance {} is referenced from spot but not available", j.getName());
                            }
                            return availability;
                        }).mapToInt(j -> install(context, j, spotPriceType, region)).sum();

            });
}

From source file:org.obiba.mica.search.JoinQueryExecutor.java

protected Function<List<MicaSearch.AggregationResultDto>, List<MicaSearch.AggregationResultDto>> aggregationPostProcessor() {
    return (aggregationResultDtos) -> {
        Map<String, AggregationResultDto.Builder> buildres = taxonomyService.getOpalTaxonomies().stream()
                .collect(Collectors.toMap(Taxonomy::getName, t -> {
                    MicaSearch.AggregationResultDto.Builder builder = MicaSearch.AggregationResultDto
                            .newBuilder().setAggregation(t.getName());
                    t.getTitle().forEach((k, v) -> builder
                            .addTitle(Mica.LocalizedStringDto.newBuilder().setLang(k).setValue(v).build()));
                    return builder;
                }));/*from  www .  j  ava 2s  .c  o m*/

        Pattern pattern = Pattern.compile("attributes-(\\w+)__(\\w+)-\\w+$");
        List<MicaSearch.AggregationResultDto> newList = Lists.newArrayList();
        // report only aggregations for which we have results
        List<String> aggregationNames = Lists.newArrayList();
        aggregationResultDtos.forEach(dto -> {
            Matcher matcher = pattern.matcher(dto.getAggregation());
            if (matcher.find()) {
                String taxonomy = matcher.group(1);
                MicaSearch.AggregationResultDto.Builder builder = buildres.get(taxonomy);
                builder.addChildren(dto);
                aggregationNames.add(builder.getAggregation());
            } else {
                newList.add(dto);
            }
        });

        newList.addAll(buildres.values().stream() //
                .filter(b -> aggregationNames.contains(b.getAggregation())) //
                .sorted(Comparator.comparing(AggregationResultDto.Builder::getAggregation)) //
                .map(MicaSearch.AggregationResultDto.Builder::build) //
                .collect(Collectors.toList())); //

        return newList;
    };
}

From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java

private Map<String, TopicVO> getTopicMetadata(String... topics) {
    if (kafkaVersion.compareTo(new Version(0, 9, 0)) >= 0) {
        return retryTemplate
                .execute(context -> brokerChannel(null).execute(channel -> getTopicMetadata(channel, topics)));
    } else {/*from w ww. j a v a 2 s .  c o m*/
        Stream<String> topicStream;
        if (topics == null || topics.length == 0) {
            topicStream = Optional.ofNullable(topicTreeCache.getCurrentChildren(ZkUtils.BrokerTopicsPath()))
                    .map(Map::keySet).map(Collection::stream).orElse(Stream.empty());
        } else {
            topicStream = Stream.of(topics);
        }

        return topicStream.map(this::getTopicZkData).filter(Objects::nonNull)
                .collect(Collectors.toMap(TopicVO::getName, topic -> topic));
    }
}

From source file:com.epam.catgenome.manager.wig.WigManager.java

private void splitWigFile(final WigFile wigFile) throws IOException {
    final Reference reference = referenceGenomeManager.loadReferenceGenome(wigFile.getReferenceId());
    final Map<String, Chromosome> chromosomeMap = reference.getChromosomes().stream()
            .collect(Collectors.toMap(BaseEntity::getName, chromosome -> chromosome));

    try (BigWigFile bigWigFile = BigWigFile.read(new File(wigFile.getPath()).toPath())) {
        readFromFile(bigWigFile, chromosomeMap, wigFile);
    }//from w  w  w.j  a v a 2s.  co m
}

From source file:com.cognifide.qa.bb.aem.touch.siteadmin.aem62.SiteadminPage.java

private void goBackUsingNavigator(String destination, String currentUrl) {
    String closestPath = navigatorDropdown.getAvailablePaths().stream().distinct()
            .filter(path -> !currentUrl.equals(path))
            .collect(Collectors.toMap(Function.identity(), path -> StringUtils.difference(path, destination)))
            .entrySet().stream().min(Comparator.comparingInt(a -> a.getValue().length())).get().getKey();
    navigatorDropdown.selectByPath(closestPath);
}