Getting return list from forEach java 8

后端 未结 2 1140
一生所求
一生所求 2021-02-08 06:07

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

相关标签:
2条回答
  • 2021-02-08 06:47

    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.

    0 讨论(0)
  • 2021-02-08 07:05

    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.

    0 讨论(0)
提交回复
热议问题