计算ArrayList中特定变量的出现次数

时间:2015-01-22 07:52:09

标签: java arraylist collections hashmap

在我的班级Feeds中,我与其他成员一起使用名为“Date”的成员变量,其类型为String。我有ArrayListFeeds个对象。我想找到具有相同日期String的对象的出现。然后可以将出现位置放在HashMap中,其中包含String日期作为键,出现次数为值。

这些方面的东西:

List<Feeds> m_feeds = new ArrayList<Feeds>();

//add all feeds objects
m_feeds.add(...);

int occurrences = 0;
HashMap<String, Integer> repeatedDatabase = new HashMap<String, Integer>();

for (Feeds f : m_feeds){
     occurrences = Collections.frequency(m_feeds, f.date);
     // i know this method compares objects but i want to know how 
    // only a single variable can be done
    repeatedDatabase.put(f.date, occurrences);
}

4 个答案:

答案 0 :(得分:1)

如果您正确地覆盖equals并在Feeds类中返回true两个具有相同日期的Feeds个实例,那么您的代码将会正常工作(因为如果您尝试将相同的键放在Map中两次,新值将覆盖旧值,因为在您的情况下,值也将是相同的,它将没有区别)。但是,每次调用Collections.frequency都会遍历整个List,这会给你一个O(n ^ 2)的时间复杂度。

提高效率的一种方法:

for (Feeds f : m_feeds){
    if (!repeatedDatabase.containsKey(f.date)) {
        occurrences = Collections.frequency(m_feeds, f.date);
        repeatedDatabase.put(f.date, occurrences);
    }
}

这仍然会进行比必要更多的迭代。对于每个唯一日期,它会调用Collections.frequency一次,这意味着您将与唯一日期一样多次迭代List。

更高效的实施根本不会使用Collection.frequency。相反,您只需在列表上迭代一次,并自己计算每个日期的出现次数。这会给你一个O(n)时间复杂度。

for (Feeds f : m_feeds){
    if (!repeatedDatabase.containsKey(f.date)) {
        repeatedDatabase.put(f.date, 1);
    } else {
        repeatedDatabase.put(f.date, repeatedDatabase.get(f.date)+1);
    }
}

答案 1 :(得分:1)

除了给你一个简单的解决方案外,我冒昧地修改你代码中的一些东西,请看看:

List<Feeds> mFeeds = new ArrayList<>(); //If you are using Java 7+ you do not need to declare explicitly the Type in Diamonds. If you aren't, ignore this. Also fixed name to adapt to Java standards.

//add all feeds objects
m_feeds.add(...);

HashMap<String, Integer> repeatedDatabase = new HashMap<>(); //See Above.

for (Feeds f : m_feeds){
    String s = f.date; //Suggestion: use a getter method, do not make public variables accessible outside class
    Integer i = repeatedDatabase.get(s);
    if (i == null){
        repeatedDatabase.put(s, 1);
    } else {
        repeatedDatabase.put(s, i+1);
    } 
}

答案 2 :(得分:0)

为什么不直接使用hashMap?

你可以做点什么

HashMap<String,Iteger> map = new HashMap<>();
for (Feeds f : m_feeds){
    if (map.contains(f.getDate()) { // use the method to get the date
        map.put(f.getDate(),map.get(f)+1);
    else
        map.put(f.getDate(),1);
}

我没有测试代码,但它应该有用。

答案 3 :(得分:0)

Angelo的答案的一个小小的更新..推动它进一步..你也可以使用字符串的地图,int []像这样

Map<String,int[]> map = new HashMap<>();
int[] countArray = map.get(key);
if(countArray == null)
   map.put(key, new int[]{0});
else
  countArray[0]++;

使用参考之美:)