use*_*388 3 java count distinct java-stream
我有Thing对象的列表:
class Thing {
public String id;
public String name;
}
Run Code Online (Sandbox Code Playgroud)
List<Thing> lst 包含以下内容:
[{'1', 'AB'},{'2', 'CD'},{'1', 'AB'},{'1','AB'},{'2','CD'},{'3','EF'}]
Run Code Online (Sandbox Code Playgroud)
现在,我想使用Java流或任何util函数来获取id的不同计数:我希望输出为:
id count
1 3
2 2
3 1
Run Code Online (Sandbox Code Playgroud)
我该如何实现?
您可以使用属性然后通过Collectors.groupingBy以下方式获取它:idcounting
List<Thing> objects = new ArrayList<>(); // initalise as in the question
Map<String, Long> countForId = objects.stream()
.collect(Collectors.groupingBy(Thing::getId, Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1883 次 |
| 最近记录: |