How to get count the same values from HashMAP?
HashMap<HashMap<String, Float>, String> HM=new HashMap<HashMap<String,Float>, String>();
HashMap<String, Float> h;
h=new HashMap<String, Float>();
h.put("X", 48.0f);
h.put("Y", 80.0f);
HM.put(typeValuesHM, "Red");
h=new HashMap<String, Float>();
h.put("X", 192.0f);
h.put("Y", 80.0f);
HM.put(typeValuesHM, "Red");
h=new HashMap<String, Float>();
h.put("X", 192.0f);
h.put("Y", 320.0f);
HM.put(typeValuesHM, "Blue");
h=new HashMap<String, Float>();
h.put("X", 336.0f);
h.put("Y", 560.0f);
HM.put(typeValuesHM, "Blue");
The values of my HashMap HM are as follows:
{ {x=48,y=80}=Red,{x=192,y=80}=Red,{x=192,y=320}=Blue,{x=336,y=560}=Blue }
Here,
I want to count the similar values in the HashMap HM.
ie) if i give value equals to "Red" means i want to get count=2. if i give value equals to "Blue" means i want to get count=2.
How to get count the same values from HashMAP HM?
You can simply write multiMap. put("DM", "123"); . And mind, that you should switch your key and value. DM should be the key.
Points to remember: Map doesn't allow duplicate keys, but it allows duplicate values. HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value. Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.
Output: The output will be as follows. In this way, we can insert multiple values associated with the same key into the HashMap using Collections.
int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
Loop through the entry set and drop all values to a second map, the first maps value as a key, the value will be the count:
Map<String, Integer> result = new TreeMap<String, Integer>();
for (Map.Entry<Map<String, Float>> entry:HM.entrySet()) {
String value = entry.getValue();
Integer count = result.get(value);
if (count == null)
result.put(value, new Integer(1));
else
result.put(value, new Integer(count+1));
}
The result map for your example should be like this:
{"Red"=2, "Blue"=2} // values are stored as Integer objects
The only way you can do it is to iterate through all the elements and count the occurrences:
for(String value: hm.values()) {
if (value.equals(valueToCompare)) {
count++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With