Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 groupingBy list of list

Let say we have an object 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);
}

}

Now, having List of Draws, I need to get a Map where key is a number in draw and value is a count (how many times that number was drawn)

For example, having

List<Draw> drawList = Arrays.asList(new Draw(1,2,5), new Draw(1,5,6));

I want to get a map like the following: {1=2, 2=1, 5=2, 6=1}

Can I implement this using new groupingBy operations of java 8 or another new feature?

Thanks.

like image 580
EasyRider Avatar asked Oct 30 '22 04:10

EasyRider


1 Answers

If I got everything right:

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}

Or obviously like this:

Map<Integer, Long> map2 = drawList
            .stream()
            .flatMap(x -> x.getResultAsList().stream())
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
like image 164
Eugene Avatar answered Nov 17 '22 09:11

Eugene