gpt4 book ai didi

java - 如何在 Java 中使用 ThreadLocalRandom.current().ints(int,int) 来查找与特定表达式匹配的特定数字?

转载 作者:行者123 更新时间:2023-12-04 10:51:51 24 4
gpt4 key购买 nike

我想使用 ThreadLocalRandom.current().ints(int,int) 生成一个 ifinite IntStream,例如:
ThreadLocalRandom.current().ints(0, 20)
据我了解,此代码将生成一个 IntStream 例如{2, 7, 4, 0, 5, 9, 3...}
然后我想要第一个匹配特定表达式的数字,例如

该数字应可被 3 整除

在这种情况下,数字应该是 9。所以问题是,如何使用流操作获得这个数字?

最佳答案

因为 ThreadLocalRandom#ints 返回无限 IntStream ,您需要使用 IntStream#filter IntStream#findFirst 短路它:

OptionalInt divisibleByThree = ThreadLocalRandom.current()
.ints(0, 20)
.filter(i -> i % 3 == 0)
.findFirst();

打印这可能会返回以下内容:
OptionalInt[12]

关于java - 如何在 Java 中使用 ThreadLocalRandom.current().ints(int,int) 来查找与特定表达式匹配的特定数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59447790/

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