16

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?

2
  • 1
    Please, study the Stream API. It has more methods than just forEach. Commented Sep 16, 2015 at 18:48
  • 1
    @Holger sometimes I look back at questions I wrote and I can't help but facepalm Commented Mar 31, 2017 at 13:10

3 Answers 3

23

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You saved my hours. Thanks. but is there a way without converting it to stream and converting it back to array? isn't it a little inefficient?
7

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.

1 Comment

There is no Collectors.toArray(). Instead, the Stream itself offers a toArray() method.
1

In my case I had to use some setter of Thing, so used peek(...)

List<Thing> functionedThings = Array.stream(things)
    .peek(thing -> thing.setSuccess(true))
    .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.