5

有谁能够帮我?我需要编写一个程序,其中有 10 个元素,arraylist我需要找到它有多少重复值,并计算和显示这些值。

例如:说我有

list = {"stack", "overflow", "stack", 
        "yahoo", "google", "msn", 
        "MSN", "stack", "overflow", "user" }

结果应该是:

stack = 3
overflow = 2
google = 1
msn = 2
yahoo =1
user = 1
4

6 回答 6

8

使用哈希映射。这是一个简单的实现

List<String> strings = new ArrayList<String>();
strings.put("stack", "overflow", "stack", "yahoo", "google", "msn", "MSN", "stack", "overflow", "user");

Map<String, Integer> counts = new HashMap<String, Integer>();

for (String str : strings) {
    if (counts.containsKey(str)) {
        counts.put(str, counts.get(str) + 1);
    } else {
        counts.put(str, 1);
    }
}

for (Map.Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}
于 2012-10-18T05:53:48.343 回答
5

使用Google Guava库的MultiSet. 它支持添加多个元素,并计算多重集包含的每个元素的出现次数。

Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<String> entry : wordsMultiset.entrySet() ){
     System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}
于 2012-10-18T05:51:44.693 回答
3

像这样使用hashmap

Map<String, Integer> occurrencies = new HashMap<String, Integer>();
for (String word : list) {
    occurrencies.put(word, occurrencies.containsKey(word)
    ? occurrencies.get(word) + 1 : 1);
}
for (Entry<String, Integer> entry : occurrencies.entrySet()) {
    System.out.println("Word: "+entry.getKey()
                     + ", occurences: "+entry.getValue());
}
于 2012-10-18T05:51:23.667 回答
2
Map<String, Integer> frequency = new HashMap<String, Integer>();
for (String element : list) {
    if (frequency.contains(element)) {
        frequency.put(element, frequency.get(element) + 1);
    }
    else {
        frequency.put(element, 1);
    }
}
for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
    System.out.print(entry.getKey() + " = " + entry.getValue() + " ");
}
System.out.println();
于 2012-10-18T05:52:38.223 回答
1

用一个HashMap

Map<String, Integer> freqMap = new HashMap<String, Integer>();
于 2012-10-18T05:51:54.977 回答
1

创建一个Map<String, Integer>,然后遍历您的ArrayList.

然后对于每个元素: -

  • 如果它已经存在于 Map 中,则Integer将该元素的值增加 1
  • 如果不存在,则添加initial Integer值为 1的元素
于 2012-10-18T05:52:17.750 回答