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.yevster.spdxtra.LicenseList.java

private LicenseList() {
    final String licenseListLocation = System.getProperty(Constants.LICENSE_LIST_LOCATION_PROPERTY);
    try {//from  w ww  . j av  a  2 s.  c  om
        Dataset dataset = DatasetFactory.create();
        try (InputStream is = StringUtils.isNotBlank(licenseListLocation)
                ? Files.newInputStream(Paths.get(licenseListLocation))
                : this.getClass().getClassLoader().getResourceAsStream("licenseList.bin")) {
            RDFDataMgr.read(dataset, is, Lang.RDFTHRIFT);
        }

        Resource mainResource = dataset.getDefaultModel().getResource(Constants.LICENSE_LIST_URL);
        version = mainResource.getProperty(SpdxProperties.LICENSE_LIST_VERSION).getString();
        retrievedListedLicenses = MiscUtils
                .toLinearStream(mainResource.listProperties(SpdxProperties.LICENSE_LIST_LICENSE))
                .map(Statement::getObject).map(RDFNode::asResource).map(ListedLicense::new)
                .collect(Collectors.toMap(ListedLicense::getLicenseId, Function.identity()));

    } catch (IOException e) {
        throw new RuntimeException("Unable to initialize license list");
    }
}

From source file:com.github.aptd.simulation.elements.graph.TestCNetwork.java

/**
 * network design test/*from w  w w  .j av a  2  s  .  c om*/
 */
@Test
public final void networkbuild() {
    Assume.assumeNotNull(m_station);
    Assume.assumeNotNull(m_track);

    final Map<String, IStation<?>> l_station = StreamUtils
            .windowed(Stream.of("Gttingen", 51.536777, 9.926074, "Kreiensen", 51.850591, 9.969346,
                    "Herzberg Harz", 51.644046, 10.329508, "Heilbad Heiligenstadt", 51.377105, 10.123940,

                    "Alfeld (Leine)", 51.984547, 9.812833, "Goslar", 51.911861, 10.420842,

                    "Hann Mnden", 51.412148, 9.657186, "Witzenhausen", 51.351333, 9.860542), 3, 3)
            .map(i -> m_station.generatesingle(i.get(0), i.get(1), i.get(2)))
            .collect(Collectors.toMap(IElement::id, i -> i));

    final IStation<?> l_goettingen = l_station.get("Gttingen");
    final IStation<?> l_kreiensen = l_station.get("Kreiensen");

    // build 8 node mini scenario, one full-qualified station with
    // different platforms and levels all other only transit station
    if (PRINTENABLE)
        System.out.println(new CNetwork(

                Stream.of(

                        m_track.generatesingle("Track 01", l_goettingen, l_station.get("Hann Mnden")),
                        m_track.generatesingle("Track 02", l_goettingen, l_station.get("Witzenhausen")),
                        m_track.generatesingle("Track 03", l_goettingen, l_kreiensen),
                        m_track.generatesingle("Track 04", l_goettingen,
                                l_station.get("Heilbad Heiligenstadt")),

                        m_track.generatesingle("Track 05", l_kreiensen, l_goettingen),
                        m_track.generatesingle("Track 06", l_kreiensen, l_station.get("Goslar")),
                        m_track.generatesingle("Track 07", l_kreiensen, l_station.get("Alfeld (Leine)")),
                        m_track.generatesingle("Track 08", l_kreiensen, l_station.get("Herzberg Harz")),

                        m_track.generatesingle("Track 09", l_station.get("Herzberg Harz"),
                                l_station.get("Heilbad Heiligenstadt")),
                        m_track.generatesingle("Track 10", l_station.get("Herzberg Harz"), l_kreiensen),

                        m_track.generatesingle("Track 11", l_station.get("Heilbad Heiligenstadt"),
                                l_station.get("Herzberg Harz")),
                        m_track.generatesingle("Track 12", l_station.get("Heilbad Heiligenstadt"),
                                l_goettingen),

                        m_track.generatesingle("Track 13", l_station.get("Alfeld (Leine)"), l_kreiensen),

                        m_track.generatesingle("Track 14", l_station.get("Goslar"), l_kreiensen),

                        m_track.generatesingle("Track 15", l_station.get("Hann Mnden"), l_goettingen),

                        m_track.generatesingle("Track 16", l_station.get("Witzenhausen"), l_goettingen)

                )));
}

From source file:io.mandrel.data.analysis.AnalysisService.java

protected Analysis buildReport(Spider spider, Blob blob) {
    Analysis report;//www .j ava 2s.  c o  m
    if (blob.getMetadata().getUri().getScheme().startsWith("http")) {
        HttpAnalysis temp = new HttpAnalysis();

        // Robots.txt
        Uri pageURL = blob.getMetadata().getUri();
        String robotsTxtUrl = pageURL.getScheme() + "://" + pageURL.getHost() + ":" + pageURL.getPort()
                + "/robots.txt";
        ExtendedRobotRules robotRules = RobotsTxtUtils.getRobotRules(robotsTxtUrl);
        temp.robotRules(robotRules);

        // Sitemaps
        if (robotRules != null && robotRules.getSitemaps() != null) {
            Map<String, List<AbstractSiteMap>> sitemaps = new HashMap<>();
            robotRules.getSitemaps().forEach(url -> {
                List<AbstractSiteMap> results = getSitemapsForUrl(url);
                sitemaps.put(url, results);
            });
            temp.sitemaps(sitemaps);
        }
        report = temp;
    } else {
        report = new Analysis();
    }

    if (spider.getExtractors() != null) {
        Map<String, Instance<?>> cachedSelectors = new HashMap<>();

        // Page extraction
        if (spider.getExtractors().getData() != null) {
            Map<String, List<Document>> documentsByExtractor = spider.getExtractors().getData().stream().map(
                    ex -> Pair.of(ex.getName(), extractorService.extractThenFormat(cachedSelectors, blob, ex)))
                    .filter(pair -> pair != null && pair.getKey() != null && pair.getValue() != null)
                    .collect(Collectors.toMap(key -> key.getLeft(), value -> value.getRight()));
            report.documents(documentsByExtractor);
        }

        // Link extraction
        if (spider.getExtractors().getOutlinks() != null) {
            Map<String, Pair<Set<Link>, Set<Link>>> outlinksByExtractor = spider.getExtractors().getOutlinks()
                    .stream().map(ol -> {
                        return Pair.of(ol.getName(), extractorService.extractAndFilterOutlinks(spider,
                                blob.getMetadata().getUri(), cachedSelectors, blob, ol));
                    }).collect(Collectors.toMap(key -> key.getLeft(), value -> value.getRight()));

            report.outlinks(Maps.transformEntries(outlinksByExtractor, (key, entries) -> entries.getLeft()));
            report.filteredOutlinks(
                    Maps.transformEntries(outlinksByExtractor, (key, entries) -> entries.getRight()));
        }

    }

    report.metadata(blob.getMetadata());
    return report;
}

From source file:org.openlmis.fulfillment.web.util.OrderExportHelper.java

/**
 * Return list of OrderLineItemDtos for a given OrderLineItem.
 *
 * @param lineItems List of OrderLineItems to be exported to Dto
 * @param orderables Map of Orderables by id
 * @return list of OrderLineItemDtos// w  w w . j av a2  s . c o m
 */
public List<OrderLineItemDto> exportToDtos(List<OrderLineItem> lineItems, Map<UUID, OrderableDto> orderables) {
    XLOGGER.entry(lineItems);
    Profiler profiler = new Profiler("EXPORT_LINE_ITEMS_TO_DTOS");
    profiler.setLogger(XLOGGER);

    Map<UUID, OrderableDto> orderablesForLines;
    if (orderables == null) {
        profiler.start("GET_ORDERABLE_IDS_FROM_LINE_ITEMS");
        Set<UUID> orderableIds = new HashSet<>(lineItems.size());
        for (OrderLineItem lineItem : lineItems) {
            orderableIds.add(lineItem.getOrderableId());
        }

        profiler.start("FIND_ORDERABLES_BY_IDS");
        orderablesForLines = orderableReferenceDataService.findByIds(orderableIds).stream()
                .collect(Collectors.toMap(OrderableDto::getId, orderable -> orderable));

    } else {
        orderablesForLines = orderables;
    }

    profiler.start("CONVERT_LINE_ITEMS_TO_DTOS");
    List<OrderLineItemDto> lineItemDtos = new ArrayList<>(lineItems.size());
    for (OrderLineItem lineItem : lineItems) {
        lineItemDtos.add(exportToDto(lineItem, orderablesForLines));
    }

    profiler.stop().log();
    XLOGGER.exit(lineItemDtos);
    return lineItemDtos;
}

From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.DockerMounts.java

public List<Mount> toMount(List<Volume> volumes) {

    if (Util.isEmpty(volumes)) {
        LOG.debug("No volumes to mount.");
        return Collections.emptyList();
    }//from www.  j a  va 2  s  . co m

    final Map<String, Volume> volumeMap = volumes.stream().collect(Collectors.toMap(o -> o.name(), o -> o));
    final List<Mount> mounts = new ArrayList<>();

    for (DockerMount dockerMount : this) {
        if (dockerMount.type().equals("volume")) {
            final Volume volume = volumeMap.get(dockerMount.source);

            if (volume == null) {
                throw new RuntimeException(
                        format("Volume with name `{0}` does not exist.", dockerMount.source()));
            }

            LOG.debug(format("Using volume `{0}`.", dockerMount.source()));
        }

        final Mount mount = Mount.builder().type(dockerMount.type()).source(dockerMount.source())
                .target(dockerMount.target()).readOnly(dockerMount.readOnly()).build();

        mounts.add(mount);
    }

    return mounts;
}

From source file:io.leishvl.core.data.mongodb.MapKeyConverters.java

/**
 * Recursively iterates over a map created from a JSON document, applying a conversion function to 
 * its keys. It guarantees that all possible inner maps are also converted.
 * @param map - a map created from a JSON document
 * @param keyConverter - a function that applies a conversion to the keys of the input map
 * @return a new map where the keys where transformed using the conversion function.
 *//*  w w w .  j  a  va2s .  c  o  m*/
@SuppressWarnings("unchecked")
private static Map<String, Object> escapeMap(final Map<String, Object> map,
        final Function<String, String> keyConverter) {
    return map.entrySet().stream().collect(Collectors.toMap(e -> keyConverter.apply(e.getKey()), e -> {
        return (e.getValue() instanceof Map) ? escapeMap((Map<String, Object>) e.getValue(), keyConverter)
                : e.getValue();
    }));
}

From source file:io.syndesis.model.WithConfigurationProperties.java

/**
 * Filters the specified properties, using the specified {@link Predicate} and value converter {@link Function}.
 *
 * @param properties        The configuration.
 * @param predicate         The {@link Predicate}.
 * @param keyConverter    The {@link Function} to apply to keys.
 * @param valueConverter    The {@link Function} to apply to values.
 * @return                  A map with the properties that match the {@link Predicate}, and converted values.
 *//*from w w w. j  a  va2 s  . c o m*/
default Map<String, String> filterProperties(Map<String, String> properties,
        Predicate<Entry<String, String>> predicate, Function<Entry<String, String>, String> keyConverter,
        Function<Entry<String, String>, String> valueConverter) {
    return properties.entrySet().stream().filter(predicate)
            .collect(Collectors.toMap(keyConverter, valueConverter));
}

From source file:com.orange.servicebroker.staticcreds.stories.get_syslog_drain_url.CreateLogDrainServiceBindingTest.java

@Test
public void create_service_binding_with_static_syslog_drain_url_set_at_service_level() throws Exception {
    given().syslog_drain_url_set_in_catalog(
            service_broker_properties_with_syslog_drain_url_at_service_level_with_requires_field_set());
    when().cloud_controller_requests_to_create_a_service_instance_binding_for_plan_id("dev-id");
    then().it_should_be_returned_with_syslog_drain_url(
            new CreateServiceInstanceAppBindingResponse().withSyslogDrainUrl("syslog://log.example.com:5000")
                    .withCredentials(Collections.unmodifiableMap(
                            Stream.of(new AbstractMap.SimpleEntry<>("URI", "http://my-api.org"))
                                    .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())))));
}

From source file:com.cognifide.qa.bb.config.YamlConfig.java

private Map<String, Map<String, String>> readAdditionalContexts() {
    Map<String, Map<String, String>> additionalContexts = new HashMap<>();

    URL contextsResource = getClass().getResource(ADDITIONAL_CONTEXTS_FOLDER);
    if (contextsResource != null) {
        try (Stream<Path> files = Files.walk(Paths.get(contextsResource.toURI()))) {
            additionalContexts.putAll(/*from  w w w.java2s  .  c  o  m*/
                    files.filter(Files::isRegularFile).filter(path -> path.toString().endsWith(YamlReader.YAML))
                            .map(this::getContextsFromYaml).map(Map::entrySet).flatMap(Collection::stream)
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
        } catch (IOException e) {
            LOG.error("Could not read the additional contexts", e);
        } catch (URISyntaxException e) {
            LOG.error("Could not parse the additional contexts folder path", e);
        }
    }
    return additionalContexts;
}

From source file:io.syndesis.model.WithProperties.java

/**
 * Filters the specified properties, using the specified {@link Predicate} and value converter {@link Function}.
 *
 * @param properties        The configuration.
 * @param predicate         The {@link Predicate}.
 * @param keyConverter    The {@link Function} to apply to keys.
 * @param valueConverter    The {@link Function} to apply to values.
 * @return                  A map with the properties that match the {@link Predicate}, and converted values.
 *//*from  www. j a  va2s.co m*/
default Map<String, String> filterProperties(Map<String, String> properties,
        Predicate<Map.Entry<String, String>> predicate,
        Function<Map.Entry<String, String>, String> keyConverter,
        Function<Map.Entry<String, String>, String> valueConverter) {
    return properties.entrySet().stream().filter(predicate)
            .collect(Collectors.toMap(keyConverter, valueConverter));
}