Having the following simple example of a java stream
Stream<Integer> s123 = Stream.of(1, 2, 3);
List<String> abc = Arrays.asList("a", "b", "c");
s123.flatMap(i -> abc.stream())
.peek(System.out::println)
.findFirst()
.ifPresent(System.out::println);
What would you expect the peek will print?
I was expecting just "a", since the findFirst
should short circuit the evaluation of the stream. Unfortunately this is not what happens. The peek method prints "a", "b", "c". This seems to be the case since the stream is created by flatMap
concatenating the same stream three times.
The problem I am facing is, if someone provides a method, which returns a stream, e.g.
Stream<String> multipleOf(int i, String ...s)
one really needs to know the implementation of this method when using the stream.
The real world example did not use peek
(which I used for illustration here), but a map operation doing some heavy work. In the end it caused some serious performance problems, since a lot more elements where mapped than expected.
So when it comes to performance, it seems to be safest to rely on the good old for loop - although I do like the streams very much.
Any thoughts on how to deal with these problems are welcome.