【问题标题】:How to add values to list from Object using stream如何使用流将值从对象添加到列表
【发布时间】:2021-11-28 05:33:42
【问题描述】:

我有一个具有多个属性的对象,我想将多个属性添加到同一个列表中

我能够添加一个属性,但找不到添加其他属性的方法。

如果可以,我们可以这样做吗?

List<MyObject> myObject = new ArrayList<>();

I have some values in the object  here 

List<Long> Ids  = myObject .stream().map(MyObject::getJobId).collect(Collectors.toList());

在这里,我想从同一个 MyObject 对象 getTestId 中再添加一个属性到列表中,有没有一种方法可以在上述相同的语句中添加?

【问题讨论】:

  • List&lt;Long&gt; Ids=myObject.stream().flatMap(o -&gt; Stream.of(o.getJobId(), o.getTestId())) .collect(Collectors.toList());

标签: java collections java-stream


【解决方案1】:

使用流创建两个列表,然后将它们组合到最后,map 只能返回一个值getJobIdgetTestId,所以你不能在同一个迭代中完成。

    List<Long> JobIds = myObject.stream().map(myObj::getJobId).collect(Collectors.toList());
    List<Long> TestIds = myObject.stream().map(myObj::getTestId).collect(Collectors.toList());
    List<Long> Ids = Stream.concat(JobIds.stream(), TestIds.stream()).collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    如果你想要一个包含 jobIds 和 testIds 的列表,那么你可以使用这样的东西:

    List<Long> ids = new ArrayList<>();
    myObject.forEach(o -> { 
        ids.add(o.getJobId());
        ids.add(o.getTestId()); 
    });
    

    【讨论】:

      【解决方案3】:

      .map 操作中,对象应映射到所需ID 的列表/流,然后应用flatMap

      List<Long> ids = myObject
              .stream()
              .map(mo -> Arrays.asList(mo.getId(), mo.getTestId()))
              .flatMap(List::stream)
              .collect(Collectors.toList());
      

      或(与 Holger 的评论相同)

      List<Long> ids = myObject
              .stream()
              .flatMap(mo -> Stream.of(mo.getId(), mo.getTestId()))
              .collect(Collectors.toList());
      

      如果ids 后面应该跟testIds,则可以连接流:

      List<Long> ids = Stream.concat(
          myObject.stream().map(MyObject::getId),
          myObject.stream().map(MyObject::getTestId)
      )
      .collect(Collectors.toList());
      

      如果要依次列出两个以上的属性,则应使用Stream.of + flatMap

      List<Long> ids = Stream.of(
          myObject.stream().map(MyObject::getId),
          myObject.stream().map(MyObject::getTestId),
          myObject.stream().map(MyObject::getAnotherId)
      )
      .flatMap(Function.identity())
      .collect(Collectors.toList());
      

      【讨论】:

        猜你喜欢
        • 2010-11-09
        • 2020-10-08
        • 2020-12-01
        • 2023-03-31
        • 2019-09-13
        • 2023-03-23
        • 2022-01-20
        • 2021-06-11
        • 2021-03-22
        相关资源
        最近更新 更多