Aru*_*r A 5 java collections arraylist
有谁能够帮我?我需要编写一个程序,其中我有10个元素arraylist,我需要找到它有多少重复值,并计算和显示值.
例如:说我有
list = {"stack", "overflow", "stack",
"yahoo", "google", "msn",
"MSN", "stack", "overflow", "user" }
Run Code Online (Sandbox Code Playgroud)
结果应该是:
stack = 3
overflow = 2
google = 1
msn = 2
yahoo =1
user = 1
Run Code Online (Sandbox Code Playgroud)
使用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());
}
Run Code Online (Sandbox Code Playgroud)
使用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());
}
Run Code Online (Sandbox Code Playgroud)
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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40806 次 |
| 最近记录: |