Java Stream API – count items of a nested list

You could use map() to get a Stream of region lists and then mapToInt to get the number of regions for each country. After that use sum() to get the sum of all the values in the IntStream: // now it's a stream of regions
                  .filter(rs -> rs != null) // remove regions lists that are null
                  .mapToInt(List::size) // stream of list sizes

Note: The benefit of using getRegions before filtering is that you don’t need to call getRegions more than once.

Leave a Comment