Get the return list from foreach Java 8
•
Java
I'm trying to use stream to deal with something. I think I have a conceptual misunderstanding I try to get an array, convert it into a stream, and put it in the array Foreach item I want to run a function and return a list of the results of the function from foreach
Basically this:
Thing[] functionedThings = Array.stream(things).forEach(thing -> functionWithReturn(thing))
Is that possible? Do I use the wrong streaming function?
Solution
You are looking for a 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; Reference Javadoc, which says it's better:
Note that the toArray (generator) method is used to convert the stream back to an array; The generator used is a function (which is actually a method reference) that returns a new array of things
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码