I got a group of Integers and I want to count the amount of max() integers my stream contains. The max() method is from within the Stream API.
I was going for something like this
int count = Arrays.stream(myIntArray)
.filter(i -> i == max())
.count();
System.out.printf("Count: %d", count);
I can't call the max() method from within my forEach() method since that's not how Streams function – so what can I do to make this work?
You can't do anything like this, not without a lot of hassle. The simplest way of writing what you want would be two stages:
int max = Arrays.stream(array).max().getAsInt();
int count = (int) Arrays.stream(array).filter(i -> i == max).count();
If you insist on doing it in one pass, I'd write something like
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];
...but honestly, the simple two-stage version is hard to beat. (And frankly I'd expect it to perform better.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With