Iterating over List of Objects inside another Object i have in the List

erykzabujca :

So i have structure like that

List<Object1> list1

class Object1{
   private List<Object2> list2
}
class Object2{
   private List<Object3> list3
} 

And i need to get count of all Objects3 instances. I am new to java-8 and streams so it's pretty confusing for me but i tried to do smth like that.

Integer count =
                list1
                .parallelStream()
                .reduce(0,(sum, q) -> q.getList2()
                        .forEach()
                        .reduce(0,(sum2, q2) -> sum2 + q2.getList3().size()));

Am i even close?

Ousmane D. :

I don't blame you, given that you're new to the stream API, but your approach is overcomplicated.

I'd personally go with this approach for simplicity & readability.

list1.stream() // Stream<Object1>
     .flatMap(s -> s.getList2().stream()) // Stream<Object2>
     .flatMap(s -> s.getList3().stream()) // Stream<Object3>
     .count(); // return the count of all Object3 instances

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323456&siteId=1