flatMap保证是懒惰的吗?
请考虑以下代码:
urls.stream()
.flatMap(url -> fetchDataFromInternet(url).stream())
.filter(...)
.findFirst()
.get();
当第一个就足够了时,会调用第二个URL吗?fetchDataFromInternet
我尝试了一个较小的示例,它看起来像预期的那样工作。即逐个处理数据,但是否可以依赖此行为?如果没有,在打电话之前打电话有帮助吗?.sequential()
.flatMap(...)
Stream.of("one", "two", "three")
.flatMap(num -> {
System.out.println("Processing " + num);
// return FetchFromInternetForNum(num).data().stream();
return Stream.of(num);
})
.peek(num -> System.out.println("Peek before filter: "+ num))
.filter(num -> num.length() > 0)
.peek(num -> System.out.println("Peek after filter: "+ num))
.forEach(num -> {
System.out.println("Done " + num);
});
输出:
Processing one
Peek before filter: one
Peek after filter: one
Done one
Processing two
Peek before filter: two
Peek after filter: two
Done two
Processing three
Peek before filter: three
Peek after filter: three
Done three
更新:使用官方的Oracle JDK8,如果这对实施很重要
答:根据下面的评论和答案,平面图部分懒惰。即完全读取第一个流,并且仅在需要时,它才会进行下一个流。读取流是渴望的,但读取多个流是懒惰的。
如果此行为是有意的,API 应允许函数返回流而不是流。Iterable
换句话说:链接