如何使用流从列表中的另一个对象检索列表

时间:2017-03-31 06:54:41

标签: java collections java-stream

我有点问题。从前面的步骤我得到这个列表:

List<Foo> fooList;

我现在需要将所有ID分开列表:

List<Integer> newListIds;

是否可以使用流来实现,可能是最简单的方法呢?

我的意见:

public class Foo {

   List<Bar> barList;

   //getter, setter
} 

public class Bar {

   private Integer id;

   //geter, setter 
}

2 个答案:

答案 0 :(得分:2)

你可以使用flatMap:

fooList.stream()
           .map(foo -> foo.barList)
           .flatMap(List::stream)
           .map(bar -> bar.id)
           .collect(Collectors.toList());

或者使用getter和setter的方法参考:

fooList.stream()
           .map(Foo::getBarList)
           .flatMap(List::stream)
           .map(Bar::getId)
           .collect(Collectors.toList());

答案 1 :(得分:0)

试试这段代码:

列出newListIds = new ArrayList();

    for(Foo item : fooList){
       newListIds.addAll(item.barList.stream()
                               .map(Bar::GetId)
                               .collect(Collectors.toList()));
    }