简体   繁体   中英

Java 8 Infinite Stream Output

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);

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...)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM