在哈希映射计数的重复值 [英] Counting duplicate values in Hashmap

查看:159
本文介绍了在哈希映射计数的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个哈希表,看起来像这样:

I have a hash map that looks like this:

HashMap<String, ArrayList<String>> varX =
        new HashMap<String, ArrayList<String>>();

和我不能为我的生活工作如何算重复值的数目。
例如,如果把(001,DM); 进入哈希映射和把(010,DM); 还有,如果有两个值的i​​nt HashMap中的ArrayList的部分怎么算。

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 因为我把两DM值到HashMap的

DM:2 as I 'put' two DM values into the Hashmap.

推荐答案

您有字符串映射到的ArrayList℃的HashMap中;弦乐&GT;

把(001,DM)此地图将不是由 @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)

根据你的榜样行为

,你想有一个的HashMap 该地图字符串字符串(即把(001,DM);

Based on your example behavior, you want a HashMap that maps String to String (i.e. put("001", "DM");

现在,假设你有:

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"

这篇关于在哈希映射计数的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆