gpt4 book ai didi

java - 如何将流减少(计数)应用于 IntStream 并将返回类型更改为 "int"

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:05:19 28 4
gpt4 key购买 nike

此代码无法编译:

public int trailingZeroes(int n) {
return IntStream.rangeClosed(1,n)
.filter(e -> (e % 5) == 0)
.count();
}

我注意到 IntStream 的返回类型存在差异方法:

int sum()long count()

当试图从上面的计数操作返回一个 int 类型时,

  • 我已经明白为什么 count() 返回一个 long 但为什么有sum() 返回比 count() 更窄的返回类型?

  • 什么是实现我在我的工作中尝试做的事情的最佳方式
    trailingZeroes 方法?

最佳答案

sum 方法返回一个 int,因为两个 int 的总和是一个 int。

count 的 Javadoc 说它等同于 mapToLong(e -> 1L).sum()。您可以使用它来进行自己的计数并返回 int,如下所示:

return IntStream.rangeClosed(1,n)
.filter(e -> (e % 5) == 0)
.map(e -> 1)
.sum();

或者,因为您实际上知道您的答案无论如何都适合 int,所以只需转换它:

return (int) IntStream.rangeClosed(1,n)
.filter(e -> (e % 5) == 0)
.count();

关于java - 如何将流减少(计数)应用于 IntStream 并将返回类型更改为 "int",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54634760/

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