javalambdajava-8java-stream

How to collect two fields of an object into the same list?


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?


Solution

  • 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());