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, M extends Map<K, U>> Collector<T, ?, M> toMap(
        Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
        BinaryOperator<U> mergeFunction, Supplier<M> mapFactory) 

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.adobe.acs.commons.mcp.model.AvailableProcessDefinitions.java

@Override
@SuppressWarnings("checkstyle:parametername")
public void activate() throws Exception {
    SlingScriptHelper sling = getSlingScriptHelper();
    User user = sling.getRequest().getResourceResolver().adaptTo(User.class);
    ProcessDefinitionFactory[] allDefinitionFactories = sling.getServices(ProcessDefinitionFactory.class, null);
    definitions = Stream.of(allDefinitionFactories).filter(o -> o.isAllowed(user))
            .collect(Collectors.toMap(ProcessDefinitionFactory::getName, o -> o, (a, b) -> a, TreeMap::new));
    String processDefinitionName = get("processDefinition", String.class);
    if (StringUtils.isEmpty(processDefinitionName)) {
        processDefinitionName = getRequest().getParameter("processDefinition");
    }//from  w  w  w . j a v  a  2  s.  c  o  m
    if (StringUtils.isNotEmpty(processDefinitionName) && definitions.containsKey(processDefinitionName)) {
        Class clazz = definitions.get(processDefinitionName).createProcessDefinition().getClass();
        fieldComponents = AnnotatedFieldDeserializer.getFormFields(clazz, sling);
    }
}

From source file:com.github.horrorho.inflatabledonkey.args.ArgsManager.java

public ArgsManager(Collection<Arg> args) {
    this.args = args.stream().collect(
            Collectors.toMap(Arg::option, Function.identity(), ArgsManager::merge, LinkedHashMap::new));
}

From source file:com.ikanow.aleph2.analytics.storm.assets.OutputBolt.java

/** Converts from a tuple of a linked hash map
 * @param t/*from  w  w  w  .java 2s. c  om*/
 * @return
 */
public static LinkedHashMap<String, Object> tupleToLinkedHashMap(final Tuple t) {
    return StreamSupport.stream(t.getFields().spliterator(), false)
            .collect(Collectors.toMap(f -> f, f -> t.getValueByField(f), (m1, m2) -> m1, LinkedHashMap::new));
}

From source file:org.homiefund.api.service.impl.DebtPreviewServiceImpl.java

@Override
@Transactional(readOnly = true)/* w  ww .j a  v  a  2s  . com*/
public DebtPreviewDTO getOverview() {
    Graph debtGraph = new Graph();

    Collection<DebtPreview> list = debtPreviewDAO
            .getTransactionsForPreview(mapper.map(userPreferencesBean.getPreferredHome(), Home.class));
    int i = 0;
    for (DebtPreview p : list) {
        i++;
        debtGraph.add(p);
    }

    Long principalID = securityService.getPrincipal().getId();
    Map<Long, BigDecimal> debtMap = debtGraph.debts(principalID);

    Map<UserDTO, BigDecimal> debtsMap = debtMap.entrySet().stream().filter(d -> !d.getKey().equals(principalID))
            .sorted(comparingByValue((o1, o2) -> o2.compareTo(o1)))
            .collect(Collectors.toMap(e -> mapper.map(userDAO.getById(e.getKey()), UserDTO.class),
                    e -> e.getValue(), (e1, e2) -> e1, LinkedHashMap::new));

    DebtPreviewDTO debts = new DebtPreviewDTO();
    debts.setOverview(debtsMap);
    debts.setTotal(debtsMap.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add));

    return debts;
}

From source file:org.jhk.pulsing.web.service.prod.helper.PulseServiceUtil.java

public static Map<Long, String> processTrendingPulseSubscribe(Set<String> tps, ObjectMapper objMapper) {

    @SuppressWarnings("unchecked")
    Map<Long, String> tpSubscriptions = Collections.EMPTY_MAP;
    final Map<String, Integer> count = new HashMap<>();

    tps.parallelStream().forEach(tpsIdValueCounts -> {

        try {//  w  w w.j av  a2s.c o m
            _LOGGER.debug(
                    "PulseServiceUtil.processTrendingPulseSubscribe: trying to convert " + tpsIdValueCounts);

            Map<String, Integer> converted = objMapper.readValue(tpsIdValueCounts,
                    _TRENDING_PULSE_SUBSCRIPTION_TYPE_REF);

            _LOGGER.debug("PulseServiceUtil.processTrendingPulseSubscribe: sucessfully converted "
                    + converted.size());

            //Structure is <id>0x07<value>0x13<timestamp> -> count; i.e. {"10020x07Mocked 10020x13<timestamp>" -> 1}
            //Need to split the String content, gather the count for the searched interval
            //and return the sorted using Java8 stream
            //TODO impl better

            Map<String, Integer> computed = converted.entrySet().stream().reduce(new HashMap<String, Integer>(),
                    (Map<String, Integer> mapped, Entry<String, Integer> entry) -> {
                        String[] split = entry.getKey()
                                .split(CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM);
                        Integer value = entry.getValue();

                        mapped.compute(split[0], (key, val) -> {
                            return val == null ? value : val + value;
                        });

                        return mapped;
                    }, (Map<String, Integer> result, Map<String, Integer> aggregated) -> {
                        result.putAll(aggregated);
                        return result;
                    });

            computed.entrySet().parallelStream().forEach(entry -> {
                Integer value = entry.getValue();

                count.compute(entry.getKey(), (key, val) -> {
                    return val == null ? value : val + value;
                });
            });

        } catch (Exception cException) {
            cException.printStackTrace();
        }
    });

    if (count.size() > 0) {
        tpSubscriptions = count.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(
                        entry -> Long.parseLong(
                                entry.getKey().split(CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM)[0]),
                        entry -> entry.getKey().split(CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM)[1],
                        (x, y) -> {
                            throw new AssertionError();
                        }, LinkedHashMap::new));
    }

    return tpSubscriptions;
}

From source file:com.geemvc.taglib.html.MessageTagSupport.java

protected List<Object> messageParameters() {
    List<Object> parameters = null;

    if (!dynamicAttributes.isEmpty()) {
        Map<Integer, Object> parameterMap = new LinkedHashMap<>();

        Set<Entry<String, Object>> entries = dynamicAttributes.entrySet();

        for (Entry<String, Object> entry : entries) {
            Matcher m = parameterPattern.matcher(entry.getKey());

            if (m.matches())
                parameterMap.put(Integer.valueOf(entry.getKey().substring(1)) - 1, entry.getValue());
        }/*ww w.  jav  a  2 s.  co m*/

        Map<Integer, Object> sortedParameters = parameterMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey,
                        Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

        parameters = new ArrayList<>(sortedParameters.values());
    }

    return parameters;
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

public static Map<String, FieldComponent> getFormFields(Class source, SlingScriptHelper sling) {
    return FieldUtils.getFieldsListWithAnnotation(source, FormField.class).stream()
            .collect(Collectors.toMap(Field::getName, f -> {
                FormField fieldDefinition = f.getAnnotation(FormField.class);
                FieldComponent component;
                try {
                    component = fieldDefinition.component().newInstance();
                    component.setup(f.getName(), f, fieldDefinition, sling);
                    return component;
                } catch (InstantiationException | IllegalAccessException ex) {
                    LOG.error("Unable to instantiate field component for " + f.getName(), ex);
                }/*from ww  w .  j a  v a 2  s. c o m*/
                return null;
            }, (a, b) -> a, LinkedHashMap::new));
}

From source file:com.thoughtworks.go.server.service.ElasticProfileService.java

public Map<String, ElasticProfile> listAll() {
    return getPluginProfiles().stream().collect(Collectors.toMap(ElasticProfile::getId,
            elasticAgentProfile -> elasticAgentProfile, (a, b) -> b, HashMap::new));
}

From source file:com.ikanow.aleph2.analytics.storm.services.MockAnalyticsContext.java

@Override
public void initializeNewContext(final String signature) {
    try {/*ww  w  .j  a  va2  s  .com*/
        // Inject dependencies
        final Config parsed_config = ConfigFactory.parseString(signature);
        final MockAnalyticsContext to_clone = static_instances.get(signature);

        if (null != to_clone) { //copy the fields            
            _service_context = to_clone._service_context;
            _core_management_db = to_clone._core_management_db;
            _distributed_services = to_clone._distributed_services;
            _index_service = to_clone._index_service;
            _storage_service = to_clone._storage_service;
            _globals = to_clone._globals;
            // (apart from bucket, which is handled below, rest of mutable state is not needed)
        } else {
            ModuleUtils.initializeApplication(Collections.emptyList(), Optional.of(parsed_config),
                    Either.right(this));

            _core_management_db = _service_context.getCoreManagementDbService(); // (actually returns the _core_ management db service)
            _distributed_services = _service_context
                    .getService(ICoreDistributedServices.class, Optional.empty()).get();
            _index_service = _service_context.getService(ISearchIndexService.class, Optional.empty()).get();
            _storage_service = _service_context.getStorageService();
            _globals = _service_context.getGlobalProperties();
        }
        // Get bucket 

        final BeanTemplate<DataBucketBean> retrieve_bucket = BeanTemplateUtils
                .from(parsed_config.getString(__MY_BUCKET_ID), DataBucketBean.class);
        _mutable_state.bucket.set(retrieve_bucket.get());
        final BeanTemplate<SharedLibraryBean> retrieve_library = BeanTemplateUtils
                .from(parsed_config.getString(__MY_TECH_LIBRARY_ID), SharedLibraryBean.class);
        _mutable_state.technology_config.set(retrieve_library.get());
        if (parsed_config.hasPath(__MY_MODULE_LIBRARY_ID)) {
            final BeanTemplate<LibraryContainerBean> retrieve_module = BeanTemplateUtils
                    .from(parsed_config.getString(__MY_MODULE_LIBRARY_ID), LibraryContainerBean.class);
            _mutable_state.library_configs.set(Optional.ofNullable(retrieve_module.get().libs)
                    .orElse(Collections.emptyList()).stream()
                    // (split each lib bean into 2 tuples, ie indexed by _id and path_name)
                    .flatMap(mod -> Arrays.asList(Tuples._2T(mod._id(), mod), Tuples._2T(mod.path_name(), mod))
                            .stream())
                    .collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (t1, t2) -> t1 // (can't happen, ignore if it does)
                            , () -> new LinkedHashMap<String, SharedLibraryBean>())));
        }

        _batch_index_service = (_crud_index_service = _index_service.getDataService()
                .flatMap(s -> s.getWritableDataService(JsonNode.class, retrieve_bucket.get(), Optional.empty(),
                        Optional.empty()))).flatMap(IDataWriteService::getBatchWriteSubservice);

        _batch_storage_service = (_crud_storage_service = _storage_service.getDataService()
                .flatMap(s -> s.getWritableDataService(JsonNode.class, retrieve_bucket.get(),
                        Optional.of(IStorageService.StorageStage.processed.toString()), Optional.empty())))
                                .flatMap(IDataWriteService::getBatchWriteSubservice);
        static_instances.put(signature, this);
    } catch (Exception e) {
        //DEBUG
        //System.out.println(ErrorUtils.getLongForm("{0}", e));         

        throw new RuntimeException(e);
    }
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public void initializeNewContext(final String signature) {
    try {/*from  w w  w .  j  av a2s .  c  om*/
        // Inject dependencies

        final Config parsed_config = ConfigFactory.parseString(signature);
        final HarvestContext to_clone = static_instances.get(signature);
        if (null != to_clone) { //copy the fields            
            _service_context = to_clone._service_context;
            _core_management_db = to_clone._core_management_db;
            _logging_service = to_clone._logging_service;
            _distributed_services = to_clone._distributed_services;
            _storage_service = to_clone._storage_service;
            _globals = to_clone._globals;
            // (apart from bucket, which is handled below, rest of mutable state is not needed)
        } else {
            ModuleUtils.initializeApplication(Collections.emptyList(), Optional.of(parsed_config),
                    Either.right(this));
            _core_management_db = _service_context.getCoreManagementDbService(); // (actually returns the _core_ management db service)
            _distributed_services = _service_context
                    .getService(ICoreDistributedServices.class, Optional.empty()).get();
            _logging_service = _service_context.getService(ILoggingService.class, Optional.empty()).get();
            _storage_service = _service_context.getStorageService();
            _globals = _service_context.getGlobalProperties();
        }
        // Get bucket 

        final BeanTemplate<DataBucketBean> retrieve_bucket = BeanTemplateUtils
                .from(parsed_config.getString(__MY_BUCKET_ID), DataBucketBean.class);
        this.setBucket(retrieve_bucket.get()); //(also checks on dedup setting)
        final BeanTemplate<SharedLibraryBean> retrieve_library = BeanTemplateUtils
                .from(parsed_config.getString(__MY_TECH_LIBRARY_ID), SharedLibraryBean.class);
        _mutable_state.technology_config.set(retrieve_library.get());
        if (parsed_config.hasPath(__MY_MODULE_LIBRARY_ID)) {
            final BeanTemplate<LibraryContainerBean> retrieve_module = BeanTemplateUtils
                    .from(parsed_config.getString(__MY_MODULE_LIBRARY_ID), LibraryContainerBean.class);
            _mutable_state.library_configs.set(Optional.ofNullable(retrieve_module.get().libs)
                    .orElse(Collections.emptyList()).stream()
                    // (split each lib bean into 2 tuples, ie indexed by _id and path_name)
                    .flatMap(mod -> Arrays.asList(Tuples._2T(mod._id(), mod), Tuples._2T(mod.path_name(), mod))
                            .stream())
                    .collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (t1, t2) -> t1 // (can't happen, ignore if it does)
                            , () -> new LinkedHashMap<String, SharedLibraryBean>())));
        }

        // Always want intermediate output service:
        _batch_intermed_storage_service = (_crud_intermed_storage_service = _storage_service.getDataService()
                .flatMap(s -> s.getWritableDataService(String.class, retrieve_bucket.get(),
                        Optional.of(IStorageService.StorageStage.json.toString()), Optional.empty())))
                                .flatMap(IDataWriteService::getBatchWriteSubservice);

        // Only create final output services for buckets that have no streaming enrichment:
        // (otherwise can still create lazily if emitObject is called)
        if (MasterEnrichmentType.none == Optional.ofNullable(retrieve_bucket.get().master_enrichment_type())
                .orElse(MasterEnrichmentType.none)) {
            initializeOptionalOutput(Optional.empty());
        }

        static_instances.put(signature, this);
    } catch (Exception e) {
        //DEBUG
        //System.out.println(ErrorUtils.getLongForm("{0}", e));         

        throw new RuntimeException(e);
    }
}