【问题标题】:How to collect two fields of an object into the same list?如何将对象的两个字段收集到同一个列表中?
【发布时间】:2015-11-09 06:22:01
【问题描述】:

我有一个商品对象,它有两个属性:firstCategoryIdsecondCategoryId。我有一个商品清单,我想获取所有类别 ID(包括 firstCategoryId 和 secondCategoryId)。

我目前的解决方案是:

List<Integer> categoryIdList = goodsList.stream().map(g->g.getFirstCategoryId()).collect(toList());
categoryIdList.addAll(goodsList.stream().map(g->g.getSecondCategoryId()).collect(toList()));

有没有更方便的方式可以在一个语句中获取所有 categoryId?

【问题讨论】:

  • 感谢美化

标签: java lambda java-8 java-stream


【解决方案1】:

您可以使用 flatMap 使用单个 Stream 管道来完成此操作:

List<Integer> cats = goodsList.stream()
                              .flatMap(c->Stream.of(c.getFirstCategoryID(),c.getSecondCategoryID()))
                              .collect(Collectors.toList());

【讨论】:

  • 如果我的第二个字段是正在收集的相同类型的流,即本例中的整数,是否有办法获得单个流?基本上我的最终流将有一个来自FirstCategoryID 的整数,然后是来自SecondCategoryIDList 的所有整数用于每种商品
猜你喜欢
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2019-10-21
  • 2016-08-24
  • 2017-06-21
  • 2021-08-19
  • 1970-01-01
  • 2013-06-23
相关资源
最近更新 更多