gpt4 book ai didi

lambda - 无限流和过滤器

转载 作者:行者123 更新时间:2023-12-05 03:14:23 25 4
gpt4 key购买 nike

我是 Java 8 Stream API 的新手,实际上我不明白为什么我的代码不起作用:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Stream.iterate(0, x -> x+3)
.filter(x -> x>10 && x<100).peek(System.out::println)
.collect(Collectors.toList());
numbers.forEach(System.out::println);
}
}

据我了解我写的流的“惰性”:

  1. 创建可被 3 整除的数字流

  2. 过滤它并给我一个范围为 (10, 100) 的数字流

  3. 将这个流收集到列表中

正如我所见,无限循环存在一些问题,因此 peek() 打印范围 (12, 99) 中的数字,这没问题,但之后它再次打印范围 (11, 98) 等中的数字。你能解释一下我哪里出错了吗?

最佳答案

编译器和运行时都不知道 filter 会过滤掉所有超过 100 的数字。因此,运行时继续生成无限整数并对它们应用过滤器。

您有多种方法可以解决此问题:

使用limit 将无限流截断为有限流。这使得以下过滤器有点不必要(如果您设置严格的限制,只有 x>10 测试仍然相关)。

public static void main(String[] args) {
List<Integer> numbers = Stream.iterate(0, x -> x+3)
.limit(34)
.filter(x -> x>10 && x<100).peek(System.out::println)
.collect(Collectors.toList());
numbers.forEach(System.out::println);
}

使用 IntStream.range 并乘以 3 :

public static void main(String[] args) {
List<Integer> numbers = IntStream.range(0, 34)
.map(x -> 3*x)
.collect(Collectors.toList());
numbers.forEach(System.out::println);
}

一般来说,Streams的“惰性”意味着它们只有在遇到终端(final)操作时才开始执行。如果操作需要处理列表中的所有元素(例如 toList),则不应向其传递无限流。

当您处理无限流时,您的选择是将其截断为有限流(使用限制)或进行不必处理流的所有元素的终端操作(示例:anyMatch、findFirst , 找到任何).

关于lambda - 无限流和过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25167000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com