问题
I have an Object of goods, which has two properties: firstCategoryId
and secondCategoryId
. I have a list of goods, and I want to get all category Ids (including both firstCategoryId and secondCategoryId).
My current solution is:
List<Integer> categoryIdList = goodsList.stream().map(g->g.getFirstCategoryId()).collect(toList());
categoryIdList.addAll(goodsList.stream().map(g->g.getSecondCategoryId()).collect(toList()));
Is there a more convenient manner I could get all the categoryIds in a single statement?
回答1:
You can do it with a single Stream
pipeline using flatMap
:
List<Integer> cats = goodsList.stream()
.flatMap(c->Stream.of(c.getFirstCategoryID(),c.getSecondCategoryID()))
.collect(Collectors.toList());
来源:https://stackoverflow.com/questions/33603486/how-to-collect-two-fields-of-an-object-into-the-same-list