9

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?

5 Answers 5

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

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
2

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++;
  }
}
1
0
int countValue(String toMatch) {
  int count = 0;
  for (String v : HM.values()) {
    if (toMatch.equals(value)) {
      count++;
    }
  }
  return count;
}

Also, it is probably overkill to use a HashMap as the key if you are just storing two values. The built in Point uses int, but it would not be hard to re-implement with float.

0
    Iterator<String> iter = HM.values().iterator();
    while(iter.hasNext()) {
        String color = iter.next();

        if(color.equals("Red")) {

        } else if(color.equals("Green")) {

        }  else if(color.equals("Blue")) {

        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.