What's the difference between groupingby and mapping in Collectors (Java)?

前端 未结 2 1537
情深已故
情深已故 2021-02-05 09:25

Take a look at this piece of code.

// group by price, uses \'mapping\' to convert List to Set
    Map&         


        
2条回答
  •  攒了一身酷
    2021-02-05 09:44

    No, the two are completely different.

    Collectors.groupingBy takes a function which creates keys and returns a collector which returns a map from keys to collections of objects in the stream which have that same key.

    Collectors.mapping, on the other hand, takes a function and another collector, and creates a new collector which first applies the function and then collects the mapped elements using the given collectors. Thus, the following are equivalent:

    items.stream().map(f).collect(c);
    items.stream().collect(Collectors.mapping(f, c));
    

    Collectors.mapping is most useful in situations where you do not have a stream, but you need to pass a collector directly. An example of such a situation is when using Collectors.groupingBy.

    items.stream().collect(Collectors.groupingBy(Item::getPrice, Collectors.toSet()))
    

    yields a Map> (assuming getPrice() returns a BigDecimal). However,

    items.stream().collect(Collectors.groupingBy(Item::getPrice,
        Collectors.mapping(Item::getName, Collectors.toSet())))
    

    returns a Map>. Before collecting the items, it first applies Item.getName to them.

提交回复
热议问题