How to get count the same values from HashMap?

29,299

Solution 1

int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");

Solution 2

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

Solution 3

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++;
  }
}
Share:
29,299
ios developer
Author by

ios developer

Updated on July 09, 2022

Comments

  • ios developer
    ios developer almost 2 years

    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?

  • Kjetil Ødegaard
    Kjetil Ødegaard over 13 years
    "foreach" is not a Java keyword.