计算Hashmap中的重复值 [英] Counting duplicate values in Hashmap
问题描述
我有一个看起来像这样的哈希映射:
HashMap>varX = new HashMap>();
而且我一生都无法计算出如何计算重复值的数量.例如,如果 put("001", "DM");
进入哈希映射,put("010", "DM");
以及,如何如果 Hashmap 的 ArrayList 部分中有两个值,则计数.
例如,输出看起来像这样:
DM:2
因为我将两个 DM 值放入"了 Hashmap.
您有一个 HashMap 将 String
映射到 ArrayList
.
在这张地图上执行 put("001", "DM")
将不会像 @Sotirios Delimanolis 在评论中指出的那样工作.>
你会得到如下错误:
方法 put(String, ArrayList) 在类型 HashMap>不适用于参数 (String, String)
根据您的示例行为,您需要一个 HashMap
将 String
映射到 String
(即 put("001","DM");
现在,假设你有:
HashMapvarX = new HashMap();
并且您想计算有多少键映射到相同的值,您可以这样做:
varX.put("001", "DM");varX.put("010", "DM");//...整数计数器 = 0;字符串计数For = "DM";for(String key : varX.keySet()) {//遍历这个 HashMap 中的所有键if(varX.get(key).equals(countingFor)) {//如果一个键映射到你需要的字符串,增加计数器计数器++;}}System.out.println(countingFor + ":" + counter);//将打印出DM:2"
I have a hash map that looks like this:
HashMap<String, ArrayList<String>> varX = new HashMap<String, ArrayList<String>>();
And I can't for the life of me work out how to count the number of duplicate values.
For example, If put("001", "DM");
into the hash map and put("010", "DM");
as well, how can count if there are two values int the ArrayList section of the Hashmap.
For example, the output would look something like this:
DM:2
as I 'put' two DM values into the Hashmap.
You have a HashMap that maps String
to ArrayList<String>
.
Doing put("001", "DM")
on this map will not work as was pointed out to you in the comments by @Sotirios Delimanolis.
You would get an error that looks like:
The method put(String, ArrayList<String>) in the type HashMap<String,ArrayList<String>> is not applicable for the arguments (String, String)
Based on your example behavior, you want a HashMap
that maps String
to String
(i.e. put("001", "DM");
Now, assuming you have that:
HashMap<String, String> varX = new HashMap<String, String>();
And you want to count how many keys map to the same value, here's how you can do that:
varX.put("001", "DM");
varX.put("010", "DM");
// ...
int counter = 0;
String countingFor = "DM";
for(String key : varX.keySet()) { // iterate through all the keys in this HashMap
if(varX.get(key).equals(countingFor)) { // if a key maps to the string you need, increment the counter
counter++;
}
}
System.out.println(countingFor + ":" + counter); // would print out "DM:2"
这篇关于计算Hashmap中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!