假设我们有一个对象 Draw:
class Draw {
private int num1, num2, num3;
public Draw (int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getNum3() {
return num3;
}
public void setNum3(int num3) {
this.num3 = num3;
}
public List<Integer> getResultAsList() {
return Arrays.asList(num1, num2, num3);
}
}
现在,有了绘制列表,我需要得到一个 map ,其中键是绘制中的数字,值是计数(绘制该数字的次数)
例如,有
List<Draw> drawList = Arrays.asList(new Draw(1,2,5), new Draw(1,5,6));
我想得到如下 map :{1=2, 2=1, 5=2, 6=1}
我可以使用 java 8 的新 groupingBy 操作或其他新功能来实现吗?
谢谢。
最佳答案
如果我做对了一切:
Map<Integer, Long> map = drawList
.stream()
.flatMap(x -> Stream.of(x.getNum1(), x.getNum2(), x.getNum3()))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map); // {1=2, 2=1, 5=2, 6=1}
或者显然是这样的:
Map<Integer, Long> map2 = drawList
.stream()
.flatMap(x -> x.getResultAsList().stream())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
关于java-8 - java 8 groupingBy 列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45192718/