0

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?

Naman
  • 27,789
  • 26
  • 218
  • 353
  • For easier searching, finding the most common occurrence is called finding the mode of a list. And judging from the other stream implementations I could find online, this is about optimal. – Aplet123 Jan 04 '21 at 13:48
  • how does `int[] flags = new int[intArray.length];for (int i : intArray) ){flags[i]++;}` even work? try for example, `intArray = {4,5,100};` – Naman Jan 04 '21 at 14:39
  • Oh, this is a simple exercise with some preconditions, I forgot to mention it. I mainly want to improve the FP implementation, thanks to Aplet223, I found what I want in that answer. – illuminated worm Jan 04 '21 at 16:05

0 Answers0