Search code examples
javaguava

Java-get most common element in a list


Does Java or Guava have something that will return most common element in a list?

List<BigDecimal> listOfNumbers=  new ArrayList<BigDecimal>(); 

[1,3,4,3,4,3,2,3,3,3,3,3]

return 3


Solution

  • This is fairly easy to implement yourself:

    public static <T> T mostCommon(List<T> list) {
        Map<T, Integer> map = new HashMap<>();
    
        for (T t : list) {
            Integer val = map.get(t);
            map.put(t, val == null ? 1 : val + 1);
        }
    
        Entry<T, Integer> max = null;
    
        for (Entry<T, Integer> e : map.entrySet()) {
            if (max == null || e.getValue() > max.getValue())
                max = e;
        }
    
        return max.getKey();
    }
    

    List<Integer> list = Arrays.asList(1,3,4,3,4,3,2,3,3,3,3,3);
    System.out.println(mostCommon(list));
    
    3
    

    If you want to handle cases where there's more then one most frequent element, you can scan the list once to determine how many times the most frequent element(s) occur, and then scan the list again, put those elements in a set and return that.