I’m trying to navigate over 3 lists (nested triple for loops) and set some values based on a match. Below is a class representation and also the triple for loops I’m iterating over and doing the setting based on a match.
My question is, how would I replace the loops included below, using the streams API?
I’m new to Java and trying to wrap my head around Java 8 features. Any help would be greatly appreciated. thank you and have a wonderful day!
Listed below are the classes involved and the loops which I want to replace with the Java 8 streams API:
Thanks very much in advance all! Have a great day!
CLASSES:
class B {
Long Id;
Long x;
String y;
Long z;
}
class A {
private Long Id;
private List<B> bList;
}
class C {
private Long Id;
private List<Long> bIds;
private String y;
private Long z;
}
NESTED FOR LOOPS:
void f(List<A> aList, List<C> cList) {
for(A a : aList) {
List<B> bList= a.getBList();
for(B b : bList) {
for(C c : cList) {
if(a.getId().equals(c.getId()) && c.getBIds().contains(b.getId())) {
b.setZ(c.getZ());
b.setY(c.getY());
}
}
}
}
}
I tend to agree with the other answer about not overcomplicating or obfuscating the logic with streams; however you could technically do something like this:
I did a little preprocessing to put the C's in a map by ID to reduce the need for extra looping. But you could have done this:
Keep in mind this second one, which is closest to your code, does overwrite values if there are duplicate IDs found. In both this code and your code, the last match wins.