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.daimler.spm.storefront.controllers.pages.MyQuotesController.java

/**
 * Set allowed actions for a given quote on model.
 *
 * @param model//  ww  w.  j  a va2  s. c  o m
 *           the MVC model
 * @param quoteCode
 *           the quote to be checked.
 */
protected void setAllowedActions(final Model model, final String quoteCode) {
    final Set<QuoteAction> actionSet = getQuoteFacade().getAllowedActions(quoteCode);

    if (actionSet != null) {
        final Map<String, Boolean> actionsMap = actionSet.stream()
                .collect(Collectors.toMap((v) -> v.getCode(), (v) -> Boolean.TRUE));
        model.addAttribute(ALLOWED_ACTIONS, actionsMap);
    }
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java

@Override
@Transactional/*from   ww  w  .  j a  v a  2 s . c om*/
public Map<String, StockProduct> gatherAsMap(String userId, String[] stockProductId) {
    List<StockProduct> stockProducts = gather(userId, stockProductId);
    return stockProducts.stream().collect(Collectors.toMap(StockProduct::getId, i -> i));
}

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

@Override
public CompletableFuture<Map<Integer, List<Integer>>> getSuccessorsWithPredecessors(final int number) {
    val legal = verifyLegalState();
    val indexTableFuture = getIndexTable();
    val historyTableFuture = getHistoryTable();
    CompletableFuture<List<Segment>> segments = getSuccessorsForSegment(number);

    CompletableFuture<Void> all = CompletableFuture.allOf(legal, segments, indexTableFuture,
            historyTableFuture);// w  ww. j  a  v  a2  s .c o  m

    return all.thenCompose(v -> {
        List<CompletableFuture<Map.Entry<Segment, List<Integer>>>> resultFutures = new ArrayList<>();
        List<Segment> successors = segments.getNow(null);
        for (Segment successor : successors) {
            List<Integer> candidates = TableHelper.findSegmentPredecessorCandidates(successor,
                    indexTableFuture.getNow(null).getData(), historyTableFuture.getNow(null).getData());
            resultFutures.add(findOverlapping(successor, candidates)
                    .thenApply(list -> new SimpleImmutableEntry<>(successor,
                            list.stream().map(Segment::getNumber).collect(Collectors.toList()))));
        }
        return FutureHelpers.allOfWithResults(resultFutures);
    }).thenApply(
            list -> list.stream().collect(Collectors.toMap(e -> e.getKey().getNumber(), e -> e.getValue())));
}

From source file:org.jodconverter.cli.Convert.java

private static final Map<String, Object> toMap(final String[] options) {

    if (options == null || options.length == 0 || options.length % 2 != 0) {
        return null;
    }//from w  ww. j  ava  2  s . c  o  m

    return IntStream.range(0, options.length).filter(i -> i % 2 == 0).boxed()
            .collect(Collectors.toMap(i -> options[i], i -> {
                final String val = options[i + 1];
                final Boolean bool = BooleanUtils.toBooleanObject(val);
                if (bool != null) {
                    return bool.booleanValue();
                }
                try {
                    return Integer.parseInt(val);
                } catch (NumberFormatException nfe) {
                    return val;
                }
            }));
}

From source file:com.okta.swagger.codegen.AbstractOktaJavaClientCodegen.java

private void handleOktaLinkedOperations(Swagger swagger) {
    // we want to move any operations defined by the 'x-okta-operations' or 'x-okta-crud' vendor extension to the model
    Map<String, Model> modelMap = swagger.getDefinitions().entrySet().stream()
            .filter(e -> e.getValue().getVendorExtensions().containsKey("x-okta-operations")
                    || e.getValue().getVendorExtensions().containsKey("x-okta-crud"))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    modelMap.forEach((k, model) -> {/*from w  w  w .  j a v  a  2s.com*/
        List<ObjectNode> linkNodes = new ArrayList<>();

        addAllIfNotNull(linkNodes, (List<ObjectNode>) model.getVendorExtensions().get("x-okta-operations"));
        addAllIfNotNull(linkNodes, (List<ObjectNode>) model.getVendorExtensions().get("x-okta-crud"));

        Map<String, CodegenOperation> operationMap = new HashMap<>();

        linkNodes.forEach(n -> {
            String operationId = n.get("operationId").textValue();

            // find the swagger path operation
            swagger.getPaths().forEach((pathName, path) -> {
                Optional<Map.Entry<HttpMethod, Operation>> operationEntry = path.getOperationMap().entrySet()
                        .stream().filter(e -> e.getValue().getOperationId().equals(operationId)).findFirst();

                if (operationEntry.isPresent()) {

                    Operation operation = operationEntry.get().getValue();

                    CodegenOperation cgOperation = fromOperation(pathName,
                            operationEntry.get().getKey().name().toLowerCase(), operation,
                            swagger.getDefinitions(), swagger);

                    boolean canLinkMethod = true;

                    JsonNode aliasNode = n.get("alias");
                    if (aliasNode != null) {
                        String alias = aliasNode.textValue();
                        cgOperation.vendorExtensions.put("alias", alias);

                        if ("update".equals(alias)) {
                            model.getVendorExtensions().put("saveable", true);
                        } else if ("delete".equals(alias)) {
                            model.getVendorExtensions().put("deletable", true);
                            cgOperation.vendorExtensions.put("selfDelete", true);
                        } else if ("read".equals(alias) || "create".equals(alias)) {
                            canLinkMethod = false;
                        }
                    }

                    // we do NOT link read or create methods, those need to be on the parent object
                    if (canLinkMethod) {

                        // now any params that match the models we need to use the model value directly
                        // for example if the path contained {id} we would call getId() instead

                        Map<String, String> argMap = createArgMap(n);

                        List<CodegenParameter> cgOtherPathParamList = new ArrayList<>();
                        List<CodegenParameter> cgParamAllList = new ArrayList<>();
                        List<CodegenParameter> cgParamModelList = new ArrayList<>();

                        cgOperation.pathParams.forEach(param -> {

                            if (argMap.containsKey(param.paramName)) {

                                String paramName = argMap.get(param.paramName);
                                cgParamModelList.add(param);

                                if (model.getProperties() != null) {
                                    CodegenProperty cgProperty = fromProperty(paramName,
                                            model.getProperties().get(paramName));
                                    param.vendorExtensions.put("fromModel", cgProperty);
                                } else {
                                    System.err.println("Model '" + model.getTitle() + "' has no properties");
                                }

                            } else {
                                cgOtherPathParamList.add(param);
                            }
                        });

                        // remove the body param if the body is the object itself
                        for (Iterator<CodegenParameter> iter = cgOperation.bodyParams.iterator(); iter
                                .hasNext();) {
                            CodegenParameter bodyParam = iter.next();
                            if (argMap.containsKey(bodyParam.paramName)) {
                                cgOperation.vendorExtensions.put("bodyIsSelf", true);
                                iter.remove();
                            }
                        }

                        // do not add the parrent path params to the list (they will be parsed from the href)
                        SortedSet<String> pathParents = parentPathParams(n);
                        cgOtherPathParamList.forEach(param -> {
                            if (!pathParents.contains(param.paramName)) {
                                cgParamAllList.add(param);
                            }
                        });

                        if (!pathParents.isEmpty()) {
                            cgOperation.vendorExtensions.put("hasPathParents", true);
                            cgOperation.vendorExtensions.put("pathParents", pathParents);
                        }

                        cgParamAllList.addAll(cgOperation.queryParams);
                        cgParamAllList.addAll(cgOperation.bodyParams);

                        // set all params to have more
                        cgParamAllList.forEach(param -> param.hasMore = true);

                        // then grab the last one and mark it as the last
                        if (!cgParamAllList.isEmpty()) {
                            CodegenParameter param = cgParamAllList.get(cgParamAllList.size() - 1);
                            param.hasMore = false;
                        }

                        cgOperation.vendorExtensions.put("allParams", cgParamAllList);
                        cgOperation.vendorExtensions.put("fromModelPathParams", cgParamModelList);

                        addOptionalExtension(cgOperation, cgParamAllList);

                        operationMap.put(cgOperation.operationId, cgOperation);

                        // mark the operation as moved so we do NOT add it to the client
                        operation.getVendorExtensions().put("moved", true);

                    }
                }
            });
        });

        model.getVendorExtensions().put("operations", operationMap.values());
    });
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

/**
 * create the platforms of all stations/*from ww  w . ja  v  a 2  s .  c  o m*/
 *
 * @param p_network network component
 * @param p_agents map with agent asl scripts
 * @param p_factory factory
 * @param p_time time reference
 * @return unmodifyable map with platforms
 */
private static Map<String, IPlatform<?>> platform(final Network p_network, final Map<String, String> p_agents,
        final IFactory p_factory, final ITime p_time) {
    final Map<String, IElement.IGenerator<IPlatform<?>>> l_generators = new ConcurrentHashMap<>();
    final Set<IAction> l_actions = CCommon.actionsFromPackage().collect(Collectors.toSet());
    return Collections.<String, IPlatform<?>>unmodifiableMap(p_network.getInfrastructure()
            .getOperationControlPoints().getOcp().parallelStream()
            .flatMap(ocp -> ocp.getAny().stream().filter(a -> a instanceof StationLayout).findAny()
                    .map(a -> ((StationLayout) a).getPlatform().stream()
                            .map(p -> new ImmutablePair<EOcp, PlatformType>(ocp, p)))
                    .orElse(Stream.of()))
            .filter(i -> i.getRight().getAgentRef() != null)
            .map(i -> l_generators
                    .computeIfAbsent(i.getRight().getAgentRef().getAgent(),
                            a -> platformgenerator(p_factory,
                                    p_agents.get(i.getRight().getAgentRef().getAgent()), l_actions, p_time))
                    .generatesingle(i.getLeft().getId() + "-track-" + i.getRight().getNumber(),
                            i.getLeft().getId()))
            .collect(Collectors.toMap(IElement::id, i -> i)));
}

From source file:io.pravega.controller.server.eventProcessor.LocalController.java

@Override
public CompletableFuture<Map<Segment, Long>> getSegmentsAtTime(Stream stream, long timestamp) {
    return controller.getSegmentsAtTime(stream.getScope(), stream.getStreamName(), timestamp)
            .thenApply(segments -> {//from   w w w.ja  va  2 s. c  o m
                return segments.entrySet().stream().collect(Collectors
                        .toMap(entry -> ModelHelper.encode(entry.getKey()), entry -> entry.getValue()));
            });
}

From source file:com.synopsys.integration.blackduck.configuration.BlackDuckServerConfigBuilder.java

/**
 * @deprecated Please use setProperties.
 *//*from  w  w  w.j a v  a  2  s  . co  m*/
@Deprecated
public BlackDuckServerConfigBuilder setFromProperties(Properties properties) {
    Map<String, String> propertiesMap = properties.stringPropertyNames().stream()
            .collect(Collectors.toMap(name -> name, name -> properties.getProperty(name)));

    return setFromProperties(propertiesMap);
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

private static Map<String, String> getQueryFromUrl(String url) throws URISyntaxException {
    return URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8")).stream()
            .collect(Collectors.toMap(p -> p.getName(), p -> p.getValue()));
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Builds a lookup table of settings 
 * @param mapping - the mapping to use//from ww w.  j ava  2  s.  c om
 * @param type - if the index has a specific type, lookup that and _default_ ; otherwise just _default
 * @return
 */
public static LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> parseDefaultMapping(
        final JsonNode mapping, final Optional<String> type,
        final Optional<DataSchemaBean.SearchIndexSchemaBean> maybe_search_index_schema,
        final Optional<DataSchemaBean.DocumentSchemaBean> maybe_document_schema,
        final SearchIndexSchemaDefaultBean search_index_schema_override, final ObjectMapper mapper) {
    //(see similar code in createComplexStringLookups)
    final boolean tokenize_by_default = maybe_search_index_schema.map(schema -> schema.tokenize_by_default())
            .orElse(true);
    final boolean dual_tokenize_by_default = Optional
            .ofNullable(search_index_schema_override.dual_tokenize_by_default()).orElse(false);

    final JsonNode default_string_mapping = ((ObjectNode) (ElasticsearchIndexUtils.getMapping(
            Tuples._2T(tokenize_by_default, dual_tokenize_by_default), search_index_schema_override, mapper,
            true))).put(TYPE_MATCH_NAME, "string").put(PATH_MATCH_NAME, "*");

    // (this is always not tokenized but inherits dual tokenization)
    final ObjectNode not_analyzed_field = ((ObjectNode) (ElasticsearchIndexUtils.getMapping(
            Tuples._2T(false, dual_tokenize_by_default), search_index_schema_override, mapper, true)))
                    .put(TYPE_MATCH_NAME, "string");

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> ret = Optional
            .ofNullable(mapping.get("mappings")).map(m -> {
                if (!m.isObject())
                    throw new RuntimeException("mappings must be object");
                return m;
            })
            .map(m -> Optional.ofNullable(m.get(type.orElse("_default_")))
                    .map(mm -> !mm.isNull() ? mm : m.get("_default_")).orElse(m.get("_default_")))
            .filter(m -> !m.isNull()).map(i -> {
                if (!i.isObject())
                    throw new RuntimeException(type + " must be object");
                return i;
            }).map(i -> {
                // OK so I have a list of dynamic_templates, and a list of properties - and then a set of string defaults to apply
                // 1) want to leave the properties alone
                // 2) then the tokenization overrides from createComplexStringLookups
                // 3) then the existing templates
                final Map<Either<String, Tuple2<String, String>>, JsonNode> override_props = createComplexStringLookups(
                        maybe_search_index_schema, search_index_schema_override, mapper);

                // ensure string doc fields aren't analyzed
                final Map<Either<String, Tuple2<String, String>>, String> type_override = maybe_search_index_schema
                        .map(s -> s.type_override()).map(m -> buildTypeMap(m)).orElse(Collections.emptyMap());

                final Map<Either<String, Tuple2<String, String>>, JsonNode> doc_props = maybe_document_schema
                        .map(ds -> ds.deduplication_fields())
                        .<Map<Either<String, Tuple2<String, String>>, JsonNode>>map(fields -> {
                            return fields.stream().filter(f -> !override_props.containsKey(Either.left(f)))
                                    .filter(f -> !override_props.containsKey(Either.right(Tuples._2T(f, "*"))))
                                    .filter(f -> !type_override.containsKey(Either.left(f)))
                                    .filter(f -> !type_override.containsKey(Either.right(Tuples._2T(f, "*"))))
                                    .<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>map(
                                            f -> Tuples._2T(Either.right(Tuples._2T(f, "string")),
                                                    not_analyzed_field.deepCopy().put(PATH_MATCH_NAME, f)))
                                    .collect(Collectors.toMap(
                                            (Tuple2<Either<String, Tuple2<String, String>>, JsonNode> t2) -> t2
                                                    ._1(),
                                            t2 -> t2._2()));
                        }).orElse(Collections.emptyMap());

                final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> props = new LinkedHashMap<>();
                props.putAll(doc_props); // (put these first - though actually i'm fixing the order with an explicit sort in the columnar section)
                props.putAll(override_props);

                // extra mappings and extra templates
                Optionals.of(() -> search_index_schema_override.extra_field_mappings())
                        .map(o -> mapper.convertValue(o, JsonNode.class)).ifPresent(j -> {
                            props.putAll(getTemplates(j, default_string_mapping, props.keySet()));
                            props.putAll(getProperties(j));
                        });

                // full mappings at the end
                props.putAll(getTemplates(i, default_string_mapping, props.keySet()));
                props.putAll(getProperties(i));

                return props;
            }).orElse(new LinkedHashMap<>());

    return ret;
}