Nested lists with streams in Java8

  • A+
Category:Languages

I have a list of objects A. Each object A in this list contains list of object B and the object B contains list of Object C. The object C contains an attribute name that i want to use to filter using java 8.

how to write the code below in java 8 using streams to avoid nested loop :

C c1 = null; String name = "name1" for (A a: listOfAObjects) {     for (B b: a.getList()) {         for (C c: b.getPr()) {             if (c.getName().equalsIgnoreCase(name)) {                 c1= c;                 break;             }         }     } } 

 


You can use two flatMap then a filter then you can pick the first one or if no result return null :

C c1 = listOfAObjects.stream()         .flatMap(a -> a.getList().stream())         .flatMap(b -> b.getPr().stream())         .filter(c -> c.getName().equalsIgnoreCase(name))         .findFirst()         .orElse(null); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: