Java 如何使用流从列表中的另一个对象检索列表
我有个小问题。从前面的步骤中,我得到以下列表:Java 如何使用流从列表中的另一个对象检索列表,java,collections,java-stream,Java,Collections,Java Stream,我有个小问题。从前面的步骤中,我得到以下列表: List<Foo> fooList; List傻瓜; 现在,我需要将所有id添加到单独的列表中: List<Integer> newListIds; 列出newListIds; 是否可以使用流来实现这一点,这可能是最简单的实现方法 我的班级: public class Foo { List<Bar> barList; //getter, setter } public class Ba
List<Foo> fooList;
List傻瓜;
现在,我需要将所有id添加到单独的列表中:
List<Integer> newListIds;
列出newListIds;
是否可以使用流来实现这一点,这可能是最简单的实现方法
我的班级:
public class Foo {
List<Bar> barList;
//getter, setter
}
public class Bar {
private Integer id;
//geter, setter
}
公共类Foo{
列表栏列表;
//盖特,塞特
}
公共类酒吧{
私有整数id;
//盖特,塞特
}
您可以使用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());
请尝试以下代码:
List newListIds=newarraylist()
或者
map(Foo::getBarList)。flatMap(List::stream)
正确,将修改它!非常感谢@JDC,我花了一些时间来找到一个使用stream的解决方案,现在很容易:-)或者只需.flatMap(foo->foo.getBarList().stream())
,因为不需要将其分为两个步骤。
for(Foo item : fooList){
newListIds.addAll(item.barList.stream()
.map(Bar::GetId)
.collect(Collectors.toList()));
}