简体   繁体   中英

how can i create a HashMap to iterate inside lambda function?

Is there any way to create this hashmap inside the lambda function?

        Map<SaleStatus, Long> sales = new HashMap<>();
    saleStatusCounters.forEach(saleStatusCounter -> sales.put(saleStatusCounter.getStatus(), saleStatusCounter.getMatches()));

Something like this:

        saleStatusCounters.stream()
            .map(obj -> new HashMap<SaleStatus, Long>().put(obj.getStatus(), obj.getMatches()))
            .collect(Collectors.toMap(???)));

Your code is fine as is. You can, nonetheless, use streams and Collectors.toMap to get the result you want:

Map<SaleStatus, Long> sales = saleStatusCounters.stream()
    .collect(Collectors.toMap(obj -> obj.getStatus(), obj -> obj.getMatches()));

Note: this works as long as there are no collisions in the map, ie as long as you don't have two or more sale status counter objects with the same status.

In case you have more than one element in your list with the same status, you should use the overloaded version of Collectors.toMap that expects a merge function :

Map<SaleStatus, Long> sales = saleStatusCounters.stream()
    .collect(Collectors.toMap(
        obj -> obj.getStatus(), 
        obj -> obj.getMatches(),
        Long::sum));

Here Long::sum is a BinaryOperator<Long> that merges two values that are mapped to the same key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM