我正在尝试将流用于某些事情,但我认为我在概念上存在误解。我正在尝试获取一个数组,将其转换为一个流,然后 .forEach 数组中的项目我想运行一个函数并从 foreach 返回该函数的结果列表。
本质上是这样的:
Thing[] functionedThings = Array.stream(things).forEach(thing -> functionWithReturn(thing))
这可能吗?我是否使用了错误的流函数?
最佳答案
您要找的是 map
操作:
Thing[] functionedThings = Arrays.stream(things).map(thing -> functionWithReturn(thing)).toArray(Thing[]::new);
此方法用于将一个对象映射到另一个对象;引用 Javadoc,它说得更好:
Returns a stream consisting of the results of applying the given function to the elements of this stream.
请注意,使用 toArray(generator)
将 Stream 转换回数组方法;使用的生成器是一个函数(这里实际上是一个方法引用)返回一个新的 Thing 数组。
关于java - 从 forEach java 8 获取返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616271/