简体   繁体   中英

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);

With groupingBy:

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

Assuming class A has a getB() method.

It's pretty simple actually (assuming hashCode/equals is present in B )

as.stream()
  .collect(Collectors.groupingBy(A::getB))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM