通过计算Java 8流API进行分组 [英] Group by counting in Java 8 stream API
本文介绍了通过计算Java 8流API进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<$ c $我试图在Java 8流API中找到一种简单的方法来进行分组, C>列表与LT;字符串> list = new ArrayList<>();
list.add(Hello);
list.add(Hello);
list.add(World);
地图< String,List< String>> collect = list.stream()。collect(
Collectors.groupingBy(o - > o));
System.out.println(collect);
列表< String []> collect2 = collect
.entrySet()
.stream()
.map(e - > new String [] {e.getKey(),
String.valueOf(e .getValue()。size())})
.collect(Collectors.toList());
collect2.forEach(o - > System.out.println(o [0] +>>+ o [1]));
非常感谢您的输入。
我想你只是在寻找 overload ,这需要另一个 Collector
来指定如何处理每个群组......然后 Collectors.counting()
来进行计数:
import java.util。*;
import java.util.stream。*;
class Test {
public static void main(String [] args){
List< String> list = new ArrayList<>();
list.add(Hello);
list.add(Hello);
list.add(World);
地图< String,Long> counting = list.stream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(盘点);
$ / code $ / pre
$ b $结果:
{Hello = 2,World = 1}
(也可以使用 groupingByConcurrent
来获得更高的效率。如果在您的上下文中安全,请注意真实的代码。)
p>
I try to find a simple way in Java 8 stream API to do the grouping, I come out with this complex way!
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, List<String>> collect = list.stream().collect(
Collectors.groupingBy(o -> o));
System.out.println(collect);
List<String[]> collect2 = collect
.entrySet()
.stream()
.map(e -> new String[] { e.getKey(),
String.valueOf(e.getValue().size()) })
.collect(Collectors.toList());
collect2.forEach(o -> System.out.println(o[0] + " >> " + o[1]));
I appreciate your input.
解决方案 I think you're just looking for the overload which takes another Collector
to specify what to do with each group... and then Collectors.counting()
to do the counting:
import java.util.*;
import java.util.stream.*;
class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted);
}
}
Result:
{Hello=2, World=1}
(There's also the possibility of using groupingByConcurrent
for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)
这篇关于通过计算Java 8流API进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文