zhu*_*wei 13 java lambda java-8
我有一个商品对象,它有两个属性:firstCategoryId和secondCategoryId.我有一个商品清单,我想获得所有类别ID(包括firstCategoryId和secondCategoryId).
我目前的解决方案是:
List<Integer> categoryIdList = goodsList.stream().map(g->g.getFirstCategoryId()).collect(toList());
categoryIdList.addAll(goodsList.stream().map(g->g.getSecondCategoryId()).collect(toList()));
Run Code Online (Sandbox Code Playgroud)
有没有更方便的方式我可以在一个语句中获得所有categoryIds?
Era*_*ran 19
您可以使用以下单个Stream管道执行以下操作flatMap:
List<Integer> cats = goodsList.stream()
.flatMap(c->Stream.of(c.getFirstCategoryID(),c.getSecondCategoryID()))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)