任何人都可以帮助我吗?我需要编写一个程序,我在arraylist
中有10个元素,我需要找到它有多少重复值,并计算和显示值。
前:说我有
list = {"stack", "overflow", "stack",
"yahoo", "google", "msn",
"MSN", "stack", "overflow", "user" }
结果应该是:
stack = 3
overflow = 2
google = 1
msn = 2
yahoo =1
user = 1
答案 0 :(得分:7)
使用HashMap。这是一个简单的实现
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());
}
答案 1 :(得分: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());
}
答案 2 :(得分: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());
}
答案 3 :(得分: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();
答案 4 :(得分:1)
使用HashMap
Map<String, Integer> freqMap = new HashMap<String, Integer>();
答案 5 :(得分:1)
创建Map<String, Integer>
,然后迭代ArrayList
。
然后对每个元素: -
Integer
值增加1 initial Integer
值为1