Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams groupingBy collector

How would I get this data structure using Java 8 API?

This is my object structure:

class A {

    B b;

    public A(B b) {
        this.b = b;
    }
}

class B {

    List<A> as;

    private int i;

    public B(int i) {
        this.i = i;
    }
}

I'm trying to aggregate it to

 Map<A, List<B>> bs;

from

List<A> as = new ArrayList<>();
as.add(a1);
as.add(a2);
as.add(a3);
like image 859
Bharath Avatar asked Jan 26 '18 08:01

Bharath


1 Answers

With groupingBy:

Map<B, List<A>> bs = as.stream().collect(Collectors.groupingBy(A::getB));

Assuming class A has a getB() method.

like image 171
Eran Avatar answered Sep 22 '22 12:09

Eran