在 java 集合中计算出现次数的优雅方法 [英] Elegant way of counting occurrences in a java collection

查看:16
本文介绍了在 java 集合中计算出现次数的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一组可能重复的对象,我希望最终得到每个对象的出现次数.我通过初始化一个空的 Map,然后遍历 Collection 并将对象映射到它的计数(每次映射已经包含对象时增加计数)来完成它.

public MapcountOccurrences(集合<对象>列表){映射<对象,整数>发生映射 = 新 HashMap();对于(对象对象:列表){整数 numOccurrence =occurrenceMap.get(obj);if (numOccurrence == null) {//第一次计数发生映射.put(obj, 1);} 别的 {发生映射.put(obj, numOccurrence++);}}返回发生映射;}

对于计算出现次数的简单逻辑来说,这看起来太冗长了.有没有更优雅/更短的方法来做到这一点?我愿意接受完全不同的算法或允许更短代码的 Java 语言特定功能.

解决方案

查看 Guava 的 Multiset.几乎正是您要找的.

不幸的是,它没有 addAll(Iterable iterable) 函数,但是在您的集合上调用 add(E e) 的简单循环就足够容易了.

编辑

我的错误,它确实有一个 addAll 方法 - 因为它实现了 Collection.

Given a collection of objects with possible duplicates, I'd like end up with a count of occurrences per object. I do it by initializing an empty Map, then iterating through the Collection and mapping the object to its count (incrementing the count each time the map already contains the object).

public Map<Object, Integer> countOccurrences(Collection<Object> list) {
    Map<Object, Integer> occurrenceMap = new HashMap<Object, Integer>();
    for (Object obj : list) {
        Integer numOccurrence = occurrenceMap.get(obj);
        if (numOccurrence == null) {
            //first count
            occurrenceMap.put(obj, 1);
        } else {
            occurrenceMap.put(obj, numOccurrence++);
        }
    }
    return occurrenceMap;
}

This looks too verbose for a simple logic of counting occurrences. Is there a more elegant/shorter way of doing this? I'm open to a completely different algorithm or a java language specific feature that allows for a shorter code.

解决方案

Check out Guava's Multiset. Pretty much exactly what you're looking for.

Unfortunately it doesn't have an addAll(Iterable iterable) function, but a simple loop over your collection calling add(E e) is easy enough.

EDIT

My mistake, it does indeed have an addAll method - as it must, since it implements Collection.

这篇关于在 java 集合中计算出现次数的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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