Is there an aggregateBy method in the stream Java 8 api?

后端 未结 3 874

Run across this very interesting but one year old presentation by Brian Goetz - in the slide linked he presents an aggregateBy() method supposedly in the Stream

3条回答
  •  忘掉有多难
    2020-12-05 15:59

    The aggregate operation can be done using the Collectors class. So in the video, the example would be equivalent to :

    Map map = 
        documents.stream().collect(Collectors.groupingBy(Document::getAuthor, Collectors.summingInt(Document::getPageCount)));
    

    The groupingBy method will give you a Map>. Now you have to use a downstream collector to sum all the page count for each document in the List associated with each key.

    This is done by providing a downstream collector to groupingBy, which is summingInt, resulting in a Map.


    They give basically the same example in the documentation where they compute the sum of the employees' salary by department.

    I think that they removed this operation and created the Collectors class instead to have a useful class that contains a lot of reductions that you will use commonly.

提交回复
热议问题