问题描述
给定一组可能重复的对象,我希望最终得到每个对象的出现次数.我通过初始化一个空的 Map
,然后遍历 Collection
并将对象映射到它的计数(每次映射已经包含对象时增加计数)来完成它.
public MapcountOccurrences(集合列表){映射发生映射 = 新 HashMap();对于(对象对象:列表){整数 numOccurrence =occurrenceMap.get(obj);if (numOccurrence == null) {//第一次计数发生映射.put(obj, 1);} 别的 {发生映射.put(obj, numOccurrence++);}}返回发生映射;}
对于计算出现次数的简单逻辑来说,这看起来太冗长了.有没有更优雅/更短的方法来做到这一点?我愿意接受完全不同的算法或允许更短代码的 Java 语言特定功能.
查看 Guava 的 Multiset.几乎正是您要找的.p>
不幸的是,它没有 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 集合中计算出现次数的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!