Java Stream API - count items of a nested list

前端 未结 3 664
情歌与酒
情歌与酒 2020-12-05 23:40

Let\'s assume that we have a list of countries: List and each country has a reference to a list of its regions: List

相关标签:
3条回答
  • 2020-12-06 00:17

    You may map each country to number of regions and then reduce result using sum:

    countries.stream()
      .map(c -> c.getRegions() == null ? 0 : c.getRegions().size())
      .reduce(0, Integer::sum);
    
    0 讨论(0)
  • 2020-12-06 00:22

    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:

    countries.stream().map(Country::getRegions) // now it's a stream of regions
                      .filter(rs -> rs != null) // remove regions lists that are null
                      .mapToInt(List::size) // stream of list sizes
                      .sum();
    

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

    0 讨论(0)
  • 2020-12-06 00:32

    You could even use flatMap() like:

    countries.stream().map(Country::getRegions).flatMap(List::stream).count();
    
    where,
    
    map(Country::getRegions) = returns a Stream<List<Regions>>
    flatMap(List::stream) = returns a Stream<Regions>
    
    0 讨论(0)
提交回复
热议问题