为了完整起见,这里是如何将重复项“减少”到只剩一个的方法。
如果您对最后一个OK,那就可以。
Map<String, Person> phoneBook = people.stream()
.collect(groupingBy(x -> x.name, reducing(null, identity(), (first, last) -> last)));
如果你只想要第一个:
Map<String, Person> phoneBook = people.stream()
.collect(groupingBy(x -> x.name, reducing(null, identity(), (first, last) -> first != null ? first : last)));
如果你想要最后一个但是“地址为字符串”(不使用identity()
作为参数)。
Map<String, String> phoneBook = people.stream()
.collect(groupingBy(x -> x.name, reducing(null, x -> x.address, (first, last) -> last)));
来源
因此,本质上,groupingBy
与reducing
收集器配对使用时,开始表现得非常类似于toMap
收集器,具有类似于其mergeFunction的东西...并且具有相同的最终结果...