Java-获取列表中最常见的元素

时间:2013-09-26 14:36:41

标签: java guava

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

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

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

返回3

10 个答案:

答案 0 :(得分:22)

这很容易实现:

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

如果要处理多于一个最常见元素的情况,可以扫描列表一次以确定最常见元素出现的次数,然后再次扫描列表,将这些元素放入设置并返回。

答案 1 :(得分:15)

可能是番石榴最简单的解决方案似乎是

Multiset<BigDecimal> multiset = HashMultiset.create(listOfNumbers);
BigDecimal maxElement = null;
int maxCount = 0;
for (Multiset.Entry<BigDecimal> entry : multiset.entrySet()) {
  if (entry.getCount() > maxCount) {
    maxElement = entry.getElement();
    maxCount = entry.getCount();
  }
}

这是一个完整的解决方案,比我见过的其他替代方案更短。

答案 2 :(得分:15)

In statistics, this is called the "mode"。 vanilla Java 8解决方案如下所示:

Stream.of(1, 3, 4, 3, 4, 3, 2, 3, 3, 3, 3, 3)
      .collect(Collectors.groupingBy(Functions.identity(), Collectors.counting()))
      .entrySet()
      .stream()
      .max(Comparator.comparing(Entry::getValue))
      .ifPresent(System.out::println);

哪个收益率:

3=8

jOOλ是一个支持流上mode()的库。以下程序:

System.out.println(
    Seq.of(1, 3, 4, 3, 4, 3, 2, 3, 3, 3, 3, 3)
       .mode()
);

收率:

Optional[3]

为简单起见,我省略了使用BigDecimal。不过,解决方案是一样的。

(免责声明:我为jOOλ背后的公司工作)

答案 3 :(得分:10)

这是一个纯粹的 Java 8 解决方案(注意:请勿使用此解决方案,请参阅下文):

List<Integer> theList = Arrays.asList(1, 3, 4, 3, 4, 3, 2, 3, 3, 3, 3, 3);
Integer maxOccurredElement = theList.stream()
        .reduce(BinaryOperator.maxBy((o1, o2) -> Collections.frequency(theList, o1) -
                        Collections.frequency(theList, o2))).orElse(null);
System.out.println(maxOccurredElement);

另一个解决方案,通过按频率将元素收集到地图中,然后找到具有最大值的条目并返回其密钥(基本上使用Java 8编写的arshajii's answer上的相同解决方案):

Integer maxVal = theList.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet().stream().max((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
                .map(Map.Entry::getKey).orElse(null);

更新:如果最常见的元素不止一个,并且您希望将它们全部放入集合中,我建议使用两种方法:

方法A:将原始集合收集到地图中,其中键作为元素,值作为其出现次数,获取具有最大值的条目并过滤值等于此值的映射条目我们找到的最大值(如果)。像这样:

Map<Integer, Long> elementCountMap = theList.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
List<Integer> result = elementCountMap.values().stream()
        .max(Long::compareTo).map(maxValue -> elementCountMap.entrySet().stream()
            .filter(entry -> maxValue.equals(entry.getValue())).map(Map.Entry::getKey).collect(Collectors.toList()))
        .orElse(Collections.emptyList());

方法B:将原始集合收集到地图中,其中键作为元素,值作为出现次数,将此地图转换为新地图,其中键为出现次数,值为具有此次出现次数的元素列表。然后使用自定义比较器查找此映射的max元素,该比较器比较键并获取此条目的值。像这样:

List<Integer> result = theList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    .entrySet().stream()
    .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
    .entrySet().stream().max((o1, o2) -> o1.getKey().compareTo(o2.getKey())).map(Map.Entry::getValue)
    .orElse(Collections.emptyList());

答案 4 :(得分:7)

番石榴提供的method会有所帮助,虽然效率低于路易斯的解决方案。

BigDecimal mostCommon = 
    Multisets.copyHighestCountFirst(ImmutableMultiset.copyOf(listOfNumbers))
        .iterator().next();

答案 5 :(得分:3)

执行此操作的经典方法是对列表进行排序,然后逐个完成:

public static BigInteger findMostCommon(List<BigInteger> list) {
    Collections.sort(list);
    BigInteger mostCommon = null;
    BigInteger last = null;
    int mostCount = 0;
    int lastCount = 0;
    for (BigInteger x : list) {
        if (x.equals(last)) {
            lastCount++;
        } else if (lastCount > mostCount) {
            mostCount = lastCount;
            mostCommon = last;
        }
        last = x;
    }
    return mostCommon;
}

这比使用哈希计数计数更节省空间,因为它对数组进行了排序。您可以将其放入泛型类并用T替换BigInteger,或者只使用Object代替BigInteger。

答案 6 :(得分:1)

以下是路易斯答案的扩展,它支持多个元素具有相同最大出现次数的情况:

private <T> List<T> getMostFrequentElements(List<T> list) {
    Multiset<T> multiset = HashMultiset.create(list);

    List<T> mostFrequents = new ArrayList<>();
    int maxCount = 0;

    for (Multiset.Entry<T> entry : multiset.entrySet()) {
        if (entry.getCount() > maxCount) {
            maxCount = entry.getCount();
            mostFrequents.clear();
            mostFrequents.add(entry.getElement());
        } else if (entry.getCount() == maxCount) {
            mostFrequents.add(entry.getElement());
        }
    }

    return mostFrequents;
}

答案 7 :(得分:1)

我们只能轻松地进行一次迭代:

public static Integer mostFrequent(List<Integer> list) {

    if (list == null || list.isEmpty())
        return null;

    Map<Integer, Integer> counterMap = new HashMap<Integer, Integer>();
    Integer maxValue = 0;
    Integer mostFrequentValue = null;

    for(Integer valueAsKey : list) {
        Integer counter = counterMap.get(valueAsKey);
        counterMap.put(valueAsKey, counter == null ? 1 : counter + 1);
        counter = counterMap.get(valueAsKey);
        if (counter > maxValue) {
            maxValue = counter;
            mostFrequentValue = valueAsKey;
        }
    }
    return mostFrequentValue;
}

答案 8 :(得分:0)

如果您愿意使用Google Guava,可以使用其MultiSet类:

MultiSet<BigNumber> numbers = HashMultiSet.create();
numberSet.addAll(list);
Set<MultiSet.Entry<BigNumber>> pairs = numbers.emtrySet();
Set<MultiSet.Entry<BigNumber>> copies = new HashSet<MultiSet.Entry<BigNumber>>(pairs);

现在,按其值降序排序copies

答案 9 :(得分:0)

找到收藏中最常出现的物品:

private <V> V findMostFrequentItem(final Collection<V> items)
{
  return items.stream()
      .filter(Objects::nonNull)
      .collect(Collectors.groupingBy(Functions.identity(), Collectors.counting())).entrySet().stream()
      .max(Comparator.comparing(Entry::getValue))
      .map(Entry::getKey)
      .orElse(null);
}
相关问题