流Java 8 api中是否有aggregateBy方法? [英] Is there an aggregateBy method in the stream Java 8 api?

查看:222
本文介绍了流Java 8 api中是否有aggregateBy方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在幻灯片中浏览Brian Goetz这个非常有趣但有一年历史的演示链接他提出了一个 aggregateBy()方法,据说在Stream API中,它应该将列表(?)的元素聚合到一个映射(给定一个默认的初始值和操纵值的方法(对于重复键也是如此) - 请参阅演示文稿中的下一张幻灯片。)

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 API, which is supposed to aggregate the elements of a list (?) to a map (given a default initial value and a method manipulating the value (for duplicate keys also) - see next slide in the presentation).

显然 Stream API 。是否有另一种方法可以在Java 8中执行类似操作?

Apparently there is no such method in the Stream API. Is there another method that does something analogous in Java 8 ?

推荐答案

可以使用 收藏家 上课。所以在视频中,示例相当于:

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

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

groupingBy 方法会给你一个 Map< String,List< Document>> 。现在,您必须使用下游收集器来汇总与每个键关联的 List 中每个文档的所有页数。

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

这是通过向 groupingBy 提供下游收集器来完成的,这是 summingInt ,产生 Map< String,Integer>

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



他们在文档中给出了基本相同的例子,他们按部门计算员工工资的总和。


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.

这篇关于流Java 8 api中是否有aggregateBy方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆