获取forEach java 8的返回列表 [英] Getting return list from forEach java 8

查看:160
本文介绍了获取forEach java 8的返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用某个流,我认为我有一个概念性的误解。我试图采取一个数组,将其转换为一个流,然后.forEach项中的数组我想运行一个函数,并返回该函数的结果列表从foreach。

本质上是这样的:
$ 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)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆