Assume I have an array of doubles that looks like the following:
Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}
I need a function th
I just created such a beautiful and small solution with the new Java 8:
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MostCommonObject {
public static void main(String[] args) {
System.out.println(mostCommonObject(new Integer[] { -4, 1, -2, 3, 1, -2, 3, 1 }));
}
public static T mostCommonObject(T[] array) {
return mostCommonObject(Arrays.asList(array));
}
public static T mostCommonObject(Collection collection) {
Map map = new HashMap<>();
collection.forEach(t -> map.compute(t, (k, i) -> i == null ? 1 : i + 1));
return map.entrySet().stream().max((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue())).get().getKey();
}
}