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:ru.anr.base.BaseParent.java

/**
 * A short-cut method for simple mapping from a collection to a map
 * /*from www.j a v a  2s. c  o  m*/
 * @param collection
 *            A collection
 * @param keyMapper
 *            A key mapper
 * @param valueMapper
 *            A value mapper
 * @return A new created map
 * 
 * @param <T>
 *            The type of collection items
 * @param <K>
 *            The type of map keys
 * @param <U>
 *            The type of map values
 */
public static <T, K, U> Map<K, U> toMap(Collection<T> collection, Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) {

    return collection.stream().collect(Collectors.toMap(keyMapper, valueMapper));
}

From source file:com.thinkbiganalytics.nifi.rest.support.NifiPropertyUtil.java

/**
 * Groups the properties by their {@see NifiProperty#getIdKey}
 * @param properties the properties to inspect
 * @return a map with the property idKey (the processgroup+processorId+propertyKey, property)
 *//* www  .  j  av  a2 s  .co m*/
public static Map<String, NifiProperty> groupPropertiesByIdKey(List<NifiProperty> properties) {
    Map<String, NifiProperty> map = new HashMap();
    if (properties != null) {
        map = properties.stream().collect(Collectors.toMap(p -> p.getIdKey(), p -> p));
    }
    return map;
}

From source file:com.ggvaidya.scinames.model.Project.java

/**
 * Returns a list of dataset rows across all datasets for a particular name.
 * /*from   ww  w  .j  a  va 2  s  . c  o  m*/
 * Note that while the API signature allows for duplicate rows to be summarized, this hasn't
 * yet been implemented: we'll return a unique dataset row from multiple datasets even where
 * the data in those rows is identical.
 * 
 * @param n The name to identify across all datasets.
 * @return A Map<DatasetRow, Set<Dataset>> indicating rows to be returned.
 */
public Map<DatasetRow, Set<Dataset>> getRowsForName(Name n) {
    Map<Dataset, Set<DatasetRow>> timepointsPerRow = getDatasets().stream()
            .collect(Collectors.toMap(tp -> tp, tp -> tp.getRowsByName(n)));

    final Map<DatasetRow, Set<Dataset>> results = new HashMap<>();
    for (Dataset tp : timepointsPerRow.keySet()) {
        Set<DatasetRow> rowsForTP = timepointsPerRow.get(tp);

        rowsForTP.forEach(r -> {
            if (!results.containsKey(r))
                results.put(r, new HashSet<>());

            results.get(r).add(tp);
        });
    }

    return results;
}

From source file:nu.yona.server.analysis.service.ActivityService.java

private <T extends IntervalActivity> Map<ZonedDateTime, Set<T>> mapToZonedDateTime(
        Map<LocalDate, Set<T>> intervalActivityEntitiesByLocalDate) {
    return intervalActivityEntitiesByLocalDate.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getValue().iterator().next().getStartTime(), Map.Entry::getValue));
}

From source file:com.epam.catgenome.manager.FeatureIndexManager.java

/**
 * Filer chromosomes that contain variations, specified by filter
 *
 * @param filterForm a {@code VcfFilterForm} to filter out chromosomes
 * @return a {@code List} of {@code Chromosome} that corresponds to specified filter
 * @throws IOException//ww  w  . j  a  v a2 s  . com
 */
public List<Chromosome> filterChromosomes(VcfFilterForm filterForm) throws IOException {
    Assert.isTrue(filterForm.getVcfFileIds() != null && !filterForm.getVcfFileIds().isEmpty(),
            MessageHelper.getMessage(MessagesConstants.ERROR_NULL_PARAM, VCF_FILE_IDS_FIELD));
    List<VcfFile> vcfFiles = vcfFileManager.loadVcfFiles(filterForm.getVcfFileIds());

    List<Chromosome> chromosomes = referenceGenomeManager.loadChromosomes(vcfFiles.get(0).getReferenceId());
    Map<Long, Chromosome> chromosomeMap = chromosomes.parallelStream()
            .collect(Collectors.toMap(BaseEntity::getId, chromosome -> chromosome));

    List<Long> chromosomeIds = featureIndexDao.getChromosomeIdsWhereVariationsPresentFacet(vcfFiles,
            filterForm.computeQuery(FeatureType.VARIATION));

    return chromosomeIds.stream().map(chromosomeMap::get).collect(Collectors.toList());
}

From source file:org.ligoj.app.plugin.prov.azure.in.ProvAzurePriceImportResource.java

/**
 * Install compute prices from the JSON file provided by Azure.
 *
 * @param context// ww  w . j  ava  2  s .c o m
 *            The update context.
 */
private void installComputePrices(final UpdateContext context) throws IOException {
    context.setInstanceTypes(itRepository.findAllBy(BY_NODE, context.getNode().getId()).stream()
            .collect(Collectors.toMap(ProvInstanceType::getName, Function.identity())));

    // Install Pay-as-you-Go, one year, three years
    installComputePrices(context, "base", 1);
    installComputePrices(context, "base-one-year", 12);
    installComputePrices(context, "base-three-year", 36);
    nextStep(context.getNode(), "flush", 1);
}

From source file:com.github.sevntu.checkstyle.ordering.MethodOrder.java

private static Map<String, Method> getAllMethods(Dependencies dependencies) {
    return dependencies.getMethods().stream()
            .collect(Collectors.toMap(MethodDefinition::getSignature, Method::new));
}

From source file:com.teradata.benchto.driver.loader.BenchmarkLoader.java

private Map<String, String> extractGlobalVariables(Map<String, Object> yaml) {
    return yaml.entrySet().stream().filter(entry -> !entry.getKey().equals(VARIABLES_KEY)).collect(Collectors
            .toMap(Entry::getKey, entry -> entry.getValue() == null ? null : entry.getValue().toString()));
}

From source file:com.streamsets.pipeline.lib.el.StringEL.java

@ElFunction(prefix = "map", name = "join", description = "Returns each element of a LIST field joined on the specified character sequence.")
public static String joinMap(@ElParam("map") Map<String, Field> map, @ElParam("separator") String separator,
        @ElParam("keyValueSeparator") String kvSeparator) {
    if (map == null) {
        return "";
    }//  www  .j  a v  a  2s.co m

    Map<String, String> mapOfStrings = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            e -> e.getValue().getValue() == null ? "null" : e.getValue().getValueAsString()));
    Joiner joiner = Joiner.on(separator);

    return joiner.withKeyValueSeparator(kvSeparator).join(mapOfStrings);
}

From source file:ch.algotrader.service.ib.IBNativeReferenceDataServiceImpl.java

private void retrieveFutures(FutureFamily securityFamily, Set<ContractDetails> contractDetailsSet) {

    // get all current futures
    List<Future> allFutures = this.futureDao.findBySecurityFamily(securityFamily.getId());
    Map<String, Future> mapByConid = allFutures.stream().filter(e -> e.getConid() != null)
            .collect(Collectors.toMap(e -> e.getConid(), e -> e));
    Map<String, Future> mapBySymbol = allFutures.stream().collect(Collectors.toMap(e -> e.getSymbol(), e -> e));

    for (ContractDetails contractDetails : contractDetailsSet) {

        Contract contract = contractDetails.m_summary;
        String conid = String.valueOf(contract.m_conId);
        if (!mapByConid.containsKey(conid)) {

            LocalDate expiration = DATE_FORMAT.parse(contract.m_expiry, LocalDate::from);
            String contractMonthString = contractDetails.m_contractMonth;
            LocalDate contractMonth = parseYearMonth(contractMonthString);

            String symbol = FutureSymbol.getSymbol(securityFamily, contractMonth,
                    this.commonConfig.getFutureSymbolPattern());
            if (!mapBySymbol.containsKey(symbol)) {
                Future future = Future.Factory.newInstance();

                final String isin = FutureSymbol.getIsin(securityFamily, contractMonth);
                String ric = FutureSymbol.getRic(securityFamily, contractMonth);

                future.setSymbol(symbol);
                future.setIsin(isin);//w w  w  . j  a  v  a 2  s .  c  o m
                future.setRic(ric);
                future.setConid(conid);
                future.setExpiration(DateTimeLegacy.toLocalDate(expiration));
                future.setMonthYear(contractMonthString);
                future.setSecurityFamily(securityFamily);
                future.setUnderlying(securityFamily.getUnderlying());

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Creating future based on IB definition: {} {}", contract.m_symbol,
                            contractDetails.m_contractMonth);
                }
                this.futureDao.save(future);
            }
        }
    }
}