Is flatMap guaranteed to be lazy? [duplicate]

Under the current implementation, flatmap is eager; like any other stateful intermediate operation (like sorted and distinct). And it’s very easy to prove : int result = Stream.of(1) .flatMap(x -> Stream.generate(() -> ThreadLocalRandom.current().nextInt())) .findFirst() .get(); System.out.println(result); This never finishes as flatMap is computed eagerly. For your example: urls.stream() .flatMap(url -> fetchDataFromInternet(url).stream()) .filter(…) .findFirst() .get(); It … Read more

Java 8 Streams FlatMap method example

It doesn’t make sense to flatMap a Stream that’s already flat, like the Stream<Integer> you’ve shown in your question. However, if you had a Stream<List<Integer>> then it would make sense and you could do this: Stream<List<Integer>> integerListStream = Stream.of( Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5) ); Stream<Integer> integerStream = integerListStream .flatMap(Collection::stream); integerStream.forEach(System.out::println); Which would print: 1 … Read more