Java Stream API - count items of a nested list

前端 未结 3 675
情歌与酒
情歌与酒 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);
    

提交回复
热议问题