[英]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. 下面的代码使用
lambda expression
创建空的Map 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
从
Stream.generate
的文档中
Returns an infinite sequential unordered stream where each element is generated by the provided
Supplier
.返回无限的顺序无序流,其中每个元素由提供的
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: 因此,您有一个无限的流,其中每个新元素都是通过调用
Supplier
来创建的,如果一个空的映射表示为{}
那么您就有一个流:
{}, {}, {}, {} ...
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)
: 这就是文档中关于
Stream.generate(Supplier)
:
Returns an infinite sequential unordered stream where each element is generated by the provided
Supplier
.返回无限的顺序无序流,其中每个元素由提供的
Supplier
生成。 This is suitable for generating constant streams, streams of random elements, etc.这适用于生成恒定流,随机元素流等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.