从 forEach java 8 获取返回列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32616271/
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
Getting return list from forEach java 8
提问by ford prefect
I am trying to use a stream for something and I think I have a conceptual misunderstanding. I am trying to take an array, convert it to a stream, and .forEach item in the array I want to run a function and return a list of the results of that function from the foreach.
我正在尝试将流用于某事,但我认为我有一个概念上的误解。我正在尝试获取一个数组,将其转换为流,以及数组中的 .forEach 项我想运行一个函数并从 foreach 返回该函数的结果列表。
Essentially this:
本质上是这样的:
Thing[] functionedThings = Array.stream(things).forEach(thing -> functionWithReturn(thing))
Is this possible? Am I using the wrong stream function?
这可能吗?我是否使用了错误的流函数?
回答by Tunaki
What you are looking for is called the map
operation:
您正在寻找的称为map
操作:
Thing[] functionedThings = Arrays.stream(things).map(thing -> functionWithReturn(thing)).toArray(Thing[]::new);
This method is used to mapan object to another object; quoting the Javadoc, which says it better:
该方法用于将一个对象映射到另一个对象;引用 Javadoc,它说得更好:
Returns a stream consisting of the results of applying the given function to the elements of this stream.
返回一个流,该流由将给定函数应用于此流的元素的结果组成。
Note that the Stream is converted back to an array using the toArray(generator)
method; the generator used is a function (it is actually a method reference here) returning a new Thing array.
请注意,使用该toArray(generator)
方法将 Stream 转换回数组;使用的生成器是一个函数(这里实际上是一个方法引用)返回一个新的 Thing 数组。