Java 8 foreach 将子对象添加到新列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39326658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:02:54 来源:igfitidea点击:
Java 8 foreach add subobject to new list
提问by Valentin Grégtheitroade
Is it possible in Java 8 to write something like this:
是否可以在 Java 8 中编写如下内容:
List<A> aList = getAList();
List<B> bList = new ArrayList<>();
for(A a : aList) {
bList.add(a.getB());
}
I think it should be a mix of following things:
我认为它应该是以下几件事的混合:
aList.forEach((b -> a.getB());
or
或者
aList.forEach(bList::add);
But I can't mix these two to obtain the desired output.
但我不能混合这两者来获得所需的输出。
采纳答案by Bohemian
Here are a few ways
这里有几个方法
aList.stream().map(A::getB).forEach(bList::add);
// or
aList.forEach(a -> bList.add(a.getB()));
or you can even create bList()
on the fly:
或者您甚至可以bList()
即时创建:
List<B> bList = aList.stream().map(A::getB).collect(Collectors.toList());