Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count lists within lists using lambdas

Tags:

java

I've got a list of some objects which each further contains another list and I would like to count the number total number of all items in those nested lists. This is how I do it now:

int accu = 0;
for (SomeObject so : objects) {
    accu += so.getListWithinObject().size();
}

But I feel like this can be written as one line using some Java 8 magic. Probably not even difficult, I just don't know how.

like image 212
Selbi Avatar asked Dec 03 '22 10:12

Selbi


1 Answers

I'll list four one-liners. Each one gives the same output:

  1. objects.stream().map(SomeObject::getListWithinObject).flatMap(List::stream).count();

  2. objects.stream().flatMap(e -> e.getListWithinObject().stream()).count();

  3. objects.stream().map(e -> e.getListWithinObject().size()).reduce(0, Integer::sum);

  4. objects.stream().mapToLong(e -> e.getListWithinObject().size()).sum();

I am sure there are other ways, too. It just shows how powerful the Stream API is; you can perform a single task in multiple ways.

Two more one-liners provided by Eritrean (in comments) without using mapping:

  1. objects.stream().collect(Collectors.summingInt(so -> so.getListWithinObject().size()));

  2. objects.stream().reduce(0, (subSum, so) -> subSum + so.getListWithinObject().size(), Integer::sum)

like image 171
Mushif Ali Nawaz Avatar answered Feb 06 '23 03:02

Mushif Ali Nawaz