Java-获取列表中最常见的元素 [英] Java-get most common element in a list

查看:113
本文介绍了Java-获取列表中最常见的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java或Guava是否会返回列表中最常见的元素?

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]

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

返回3

推荐答案

这相当容易实现自己:

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.

这篇关于Java-获取列表中最常见的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆