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.
I'll list four one-liners. Each one gives the same output:
objects.stream().map(SomeObject::getListWithinObject).flatMap(List::stream).count();
objects.stream().flatMap(e -> e.getListWithinObject().stream()).count();
objects.stream().map(e -> e.getListWithinObject().size()).reduce(0, Integer::sum);
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:
objects.stream().collect(Collectors.summingInt(so -> so.getListWithinObject().size()));
objects.stream().reduce(0, (subSum, so) -> subSum + so.getListWithinObject().size(), Integer::sum)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With