erykzabujca
erykzabujca

Reputation: 83

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

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?

Upvotes: 3

Views: 77

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

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

Upvotes: 2

Naman
Naman

Reputation: 31878

Since you need the sum of the size of the list3 within each Object2 instance, you can use flatMapToInt with a nested mapToInt to calculate the sum as:

int count = list1
        .stream()
        .flatMapToInt(obj1 -> obj1.getList2()
                .stream()
                .mapToInt(obj2 -> obj2.getList3().size()))
        .sum();

Upvotes: 0

Related Questions