I was trying to answer this question, but I did not because I don't understand Streams well enough. Please tell me if my explanation is correct or not.
My answer :
import java.util.Arrays;
import java.util.stream.Stream;
public class Temp {
public static void main(String [] args){
String [] input = {"1,2", "3,4", "5"};
String [] expected = {"1", "2", "3", "4", "5"};
String [] actual = Stream.of(input)
.flatMap(s -> Arrays.stream(s.split(",")))
.toArray(String [] :: new);
//Testing - Runs only when assertions are enabled for your JVM. Set VM args = -ea for your IDE.
assert Arrays.equals(actual, expected) : "Actual array does not match expected array!";
}
}
My explanation :
1 - Take a stream of elements (Strings in this example) and pass one element at a time to flatMap
.
QUESTION - Is this actually one element at a time ?
2 - flatMap
takes a Function
which converts an element into a Stream
. In the example, the function takes a String ("1,2") and converts it into a stream of multiple Strings ("1", "2"). The stream of multiple strings is generated by Arrays.stream(an array) which we know takes an array and converts it into a stream. That array was generated by s.split(",")
. All other elements are processed and put into this one stream.
QUESTION - Does flatMap return one Stream for all elements in input array OR one Stream per element of input array ?
3 - toArray
takes elements in the single stream it got from flatMap
and puts them into one array.