gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:35:20 25 4
gpt4 key购买 nike

在我的类Feeds中,我与其他成员一起有一个名为“Date”的成员变量,它是String类型。我有一个包含 Feeds 对象的 ArrayList。我想查找具有相同日期字符串的对象的出现情况。然后,可以将出现的次数放入 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);
}

最佳答案

除了给您一个简单的解决方案之外,我还冒昧地修复了您代码中的一些问题,请看一下:

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);
}
}

关于java - 计算 ArrayList 中特定变量的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28083665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com