Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting return list from forEach java 8

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?

like image 367
ford prefect Avatar asked Sep 16 '15 18:09

ford prefect


1 Answers

You need map not forEach

List<Thing> functionedThings = Array.stream(things).map(thing -> functionWithReturn(thing)).collect(Collectors.toList());

Or toArray() on the stream directly if you want an array, like Holger said in the comments.

like image 153
Alex Avatar answered Sep 24 '22 16:09

Alex