Determine the most common occurrence in an array

前端 未结 9 972
南方客
南方客 2020-11-29 12:28

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

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 12:41

    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();
        }
    }
    

提交回复
热议问题