So let's say that we have a string: "randomText1 randomText2" in an array, which is loaded into a Stream.
Now I go over all the lines in this stream, and I split every line at the space character.
strings
.map(string -> string.split(" "))
.flatMap(Arrays::stream)
.collect(new MyClass(string1, string2));
How can I get the both sides of the string and do whatever I want with them from there on?
From Oracle docs (Oracle doc link) I only managed to find some harder cases where one would be using a Map<>
for instance. But I fail to fit their solutions to this more simpler problem of mine.
Using flatMap
is not the right tool for the job. What you apparently want to do is
strings.map(string -> string.split(" ", 2))
.map(array -> new MyClass(array[0], array[1]))
You may process the stream further by using .collect(Collectors.toList())
to get a List<MyClass>
or .findAny()
to get a single MyClass
instance (if any).
Generally, streaming an array is only useful if you want to treat all elements uniformly, i.e. not if their position has a special meaning which has to be preserved for subsequent operations.
And if you really want to create a flat stream of words or tokens, you shouldn’t use the combination of String.split
and Arrays.stream
as that will create and fill an unnecessary intermediate array. In this case use
strings.flatMap(Pattern.compile(" ")::splitAsStream)
see Pattern.splitAsStream
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With