I wrote both the implementation of IP and FP, but the implementation of FP feels some kind of wired.
First, impl of IP:
public static int countThenMaxOf(int[] intArray) {
int[] flags = new int[intArray.length];
for (int i : intArray)
flags[i]++;
int indexOfMax = 0;
for (int i = 0; i < flags.length; i++) {
if (flags[i] >= flags[indexOfMax])
indexOfMax = i;
}
return intArray[indexOfMax];
}
Then FP version:
public static long func(int[] intArray) {
return Arrays.stream(intArray)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.map(Map.Entry::getKey)
.orElseThrow();
}
As you can see, the stream is broke in half in the middle, This feels very unnatural. In contrast, the Impl of FP in Kotlin is more beautiful:
fun func(intArray: IntArray): Int =
intArray.asSequence()
.groupingBy { it }
.eachCount()
.maxByOrNull { it.value }!!.key
Don't mind my rough exception handling.
So my question is, can the implementation of Java Stream
be improved? If so, how to do?
Am I missing something in Collectors
?