获取forEach java 8的返回列表 [英] Getting return list from forEach java 8
问题描述
本质上是这样的:
$ b $ pre $ Thing [] functionedThings = Array.stream (东西).forEach(东西 - > functionWithReturn(东西))
这可能吗?我使用错误的流功能?
你在找什么叫做 map
操作:
pre $ Thing [] functionedThings = Arrays.stream(things).map(thing - > functionWithReturn(thing))。toArray(Thing [] :: new);
此方法用于将对象映射到另一个对象;引用Javadoc,它更好地说:
返回一个流,该流包含将给定函数应用到此流的元素的结果。
请注意,流将使用 toArray(generator)$ c $方法;使用的生成器是一个函数(它实际上是一个方法引用)返回一个新的Thing数组。
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.
Essentially this:
Thing[] functionedThings = Array.stream(things).forEach(thing -> functionWithReturn(thing))
Is this possible? Am I using the wrong stream function?
What you are looking for is called the map
operation:
Thing[] functionedThings = Arrays.stream(things).map(thing -> functionWithReturn(thing)).toArray(Thing[]::new);
This method is used to map an object to another object; quoting the Javadoc, which says it better:
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.
这篇关于获取forEach java 8的返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!