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

前端 未结 2 1650
情深已故
情深已故 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:32

    Is groupingBy and Mapping interchangeable?

    No, they are completely different. groupingBy lets you create a Map where the key is the first argument passed to groupingBy and the value is a List of the element type of the Stream.

    Collectors.groupingBy(Item::getPrice) would generate a Map> (assuming Item::getPrice returns a BigDecimal. Passing the mapping Collector as an argument to Collectors.groupingBy() allows you to change the value of the output map (in your example, you change it to Set).

    For the third parameter in collect(), would I get the same output type Map if I used Collectors.toList() instead of Collectors.toSet()?

    No, you would get a Map>.

提交回复
热议问题