Intermediate flow operation & # 8594; IllegalStateException

Well, I always thought that the intermediate operations of the Java8 Stream do nothing at all until the terminal operation runs in the stream.

So why does this code call IllegalStateException?

Stream<Integer> s = Stream.of(1, 2, 3);
s.limit(1);
s.limit(1);
+4
source share
1 answer

You have come across a common misconception about Streams. Due to their smooth API, the first instinct that many developers have is that each method applied to a thread will simply return it (similarly, for example, how StringBuilder- acts myStringBuilder.append("Stack").append(" Overflow").append(" is").append(" is awesome!").

, , . Stream, , , , . , , :

Stream<Integer> s = Stream.of(1, 2, 3);
Integer i = s.limit(1).limit(1).findFirst().orElse(null); // returns 1;
+4

Source: https://habr.com/ru/post/1650766/


All Articles