在java集合中计数事件的优雅方式 [英] Elegant way of counting occurrences in a java collection

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

问题描述

给定一个具有可能重复项的对象集合,我最终得到每个对象的出现次数。我通过初始化一个空的 Map ,然后遍历 Collection 并将对象映射到它的计数(增加每次地图已经包含对象时计数)。

  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){
//第一个计数
occurrenceMap.put(obj,1);
} else {
occurrenceMap.put(obj,numOccurrence ++);
}
}
return occurrenceMap;
}

对于计数事件的简单逻辑,这看起来太冗长。有更优雅/更短的方式这样做吗?

解决方案

签出

a href =http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained> Guava的Multiset 。



不幸的是,它没有一个addAll(迭代迭代)函数,而是一个简单的循环调用add(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天全站免登陆