I have a problem to use streams in java 8, I have 3 class like this:
public Class A {
String string1A;
String string2A;
List<B> listB;
.
.
.
}
public Class B {
String string1B;
String string2B;
.
.
.
}
public Class C {
String string1A;
String string2A;
String string1B;
String string2B;
.
.
.
}
Then I have a method that returns a List of C
with all the data coming from a database, and I need to create a List A
that has all the data grouped, the grouping value is the String1A
. My idea was this:
List<A> listA = new ArrayList<A>();
Set<String> listString1A = listC.stream().map(x->x.getString1A()).distinct().collect(Collectors.toSet());
for(String stringFilter1A: listString1A){
A a = listC.stream()
.filter(x->getString1A().equals(stringFilter1A))
.map(x-> new A(x.getString1A(),x.getString2A))
.findFirst().get();
List<B> listB = listC.stream()
.filter(x->getString1A().equals(stringFilter1A))
.map(x-> new B(...))
.collect(Collectors.toList());
a.setListB(listaB);
listaA.add(a);
}
Is there a way to make such a query using only streams or trying to delete the for?
Thanks.
Here's a way that groups
c
elements byA
, mapping eachC
to a newB
:This requires class
A
to implementhashCode
andequals
consistently, based onstring1A
.Then, you simply set the
List<B>
for eachA
in the map:And the keys of your map are what you want:
Or if you really need a list: