简体   繁体   中英

Java streams: transforming map's values

Having an instance of a Map<A, Set<B>> where B is a POJO with property Integer price (among others), how do I elegantly transform this map into a Map<A, Integer> where Integer denotes the sum of prices of a given set, for each key A ?

You can use stream like this:

Map<A, Integer> result = map.entrySet().stream()
        .collect(Collectors.toMap(
                Map.Entry::getKey, 
                b -> b.getValue().stream()
                        .mapToInt(B::getPrice)
                        .sum()
                ));

That should help you out. Using the Streaming-API from Java 8: (In this example the class "PricePojo" is your B and "String" is your A)

 Map<String, Integer> newMap = map.entrySet().stream()//
.collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().stream().mapToInt(PricePojo::getPrice).sum()));

You could also go the way of implementing a Map.Entry yourself like in the following example:

    Map<String, Integer> newMap = map.entrySet().stream()//
    .map(entry -> new Map.Entry<String, Integer>() {
    private int sum = entry.getValue().stream().mapToInt(PricePojo::getPrice).sum();
    @Override
    public String getKey() {
        return entry.getKey();
    }

    @Override
    public Integer getValue() {
        return sum;
    }

    @Override
    public Integer setValue(Integer value) {
        return sum = value.intValue();
    }
    }).collect(Collectors.toMap(Entry::getKey, Entry::getValue));

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