21

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?

0

1 Answer 1

37

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());
1
  • Is there a way to have a single stream if my second field is a stream of same type that is being collected i.e. Integer in this example? Basically my final stream would have an Integer from FirstCategoryID and then all Integers from SecondCategoryIDList for each goods
    – ankitkpd
    Commented Aug 24, 2021 at 19:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.