В Java 8+ это можно сделать так:
public static int[] modes(int[] marksArray) {
Entry<Long, List<Integer>> max = Arrays.stream(marksArray).boxed()
.collect(groupingBy(identity(), TreeMap::new, counting())).entrySet().stream()
.filter(e -> e.getValue() > 1)
.collect(groupingBy(Entry::getValue, TreeMap::new, mapping(Entry::getKey, toList())))
.lastEntry();
return (max == null ? new int[0] : max.getValue().stream().mapToInt(Integer::intValue).toArray());
}
Тест
public static void main(String[] args) {
// Samples from https://www.mathsisfun.com/mode.html
// and https://www.purplemath.com/modules/meanmode.htm
test(); // []
test(1, 2, 4, 7); // []
test(6, 3, 9, 6, 6, 5, 9, 3); // [6]
test(1, 3, 3, 3, 4, 4, 6, 6, 6, 9); // [3, 6]
test(13, 18, 13, 14, 13, 16, 14, 21, 13); // [13]
test(8, 9, 10, 10, 10, 11, 11, 11, 12, 13); // [10, 11]
}
public static void test(int... marksArray) {
System.out.println(Arrays.toString(modes(marksArray)));
}
Выход
[]
[]
[6]
[3, 6]
[13]
[10, 11]