Java 8 Streams grouped into a collector

How can I get this data structure using java 8 streams.

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

This is my object structure. Im trying to combine it,

  Map<A, List<B>> bs 

from,

 List<A> as = new ArrayList<>(); as.add(a1); as.add(a2); as.add(a3); 
+5
source share
2 answers

Grouped By:

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

Assuming class A has a getB() method.

+7
source

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

 as.stream() .collect(Collectors.groupingBy(A::getB)) 
+7
source

Source: https://habr.com/ru/post/1274963/


All Articles