Reputation: 8303
Below code creates empty Map Stream
using lambda expression
and the next line is used to output any element in the stream. But upon running the code it is giving infinite output. I don't know why because it should print {}
once as the map is empty. Can someone explains what is going on?
Stream<Map<String,String>> mapStream = Stream.generate(() -> {
return Collections.emptyMap();
});
mapStream.forEach(System.out::println);
Upvotes: 1
Views: 534
Reputation: 61148
From the documentation for Stream.generate
Returns an infinite sequential unordered stream where each element is generated by the provided
Supplier
. This is suitable for generating constant streams, streams of random elements, etc.
So you have an infinite stream, where each new element is created by calling the Supplier
, if an empty map is represented as {}
then you have a stream of:
{}, {}, {}, {} ...
What you are looking for is:
Stream.of(Collections.emptyMap()).forEach(System.out::println);
Which will print just {}
. (although why you would want this is somewhat beyond me...)
Upvotes: 6
Reputation: 72854
This is what the documentation says about Stream.generate(Supplier)
:
Returns an infinite sequential unordered stream where each element is generated by the provided
Supplier
. This is suitable for generating constant streams, streams of random elements, etc.
Upvotes: 2