Getting return list from forEach java 8

后端 未结 2 1137
一生所求
一生所求 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.

提交回复
热议问题