gpt4 book ai didi

java - 在 Java 8 中的当前流方法中使用 Stream 方法

转载 作者:行者123 更新时间:2023-12-02 11:12:18 24 4
gpt4 key购买 nike

我有一组整数,我想计算流中包含的 max() 整数的数量。 max() 方法来自 Stream API。

我想要这样的东西

int count = Arrays.stream(myIntArray)
.filter(i -> i == max())
.count();
System.out.printf("Count: %d", count);

我无法从我的 forEach() 方法中调用 max() 方法,因为这不是 Streams 的功能 – 那么我该怎么做才能完成这项工作?

最佳答案

你不能做这样的事情,这会带来很多麻烦。编写您想要的内容的最简单方法是两个阶段:

int max = Arrays.stream(array).max().getAsInt();
int count = (int) Arrays.stream(array).filter(i -> i == max).count();

如果您坚持一次性完成,我会写类似的内容

int[] maxAndCount = Arrays.stream(array).collect(
() -> new int[2], // first max, then count
(maxAndCount, i) -> {
if (i > maxAndCount[0] || maxAndCount[1] == 0) {
maxAndCount[0] = i;
maxAndCount[1] = 1;
} else if (i == maxAndCount[0]) {
maxAndCount[1]++;
}
},
(maxAndCount1, maxAndCount2) -> {
if (maxAndCount1[0] < maxAndCount2[0]) {
maxAndCount1[0] = maxAndCount2[0];
maxAndCount1[1] = maxAndCount2[1];
} else if (maxAndCount1[0] == maxAndCount2[0]) {
maxAndCount1[1] += maxAndCount2[1];
}
});
int count = maxAndCount[1];

...但老实说,简单的两阶段版本很难被击败。 (坦率地说,我希望它能表现得更好。)

关于java - 在 Java 8 中的当前流方法中使用 Stream 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417217/

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