Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get count the same values from HashMap?

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?

like image 433
ios developer Avatar asked Feb 25 '11 12:02

ios developer


People also ask

How count duplicate values in HashMap?

You can simply write multiMap. put("DM", "123"); . And mind, that you should switch your key and value. DM should be the key.

Can Map contains duplicates?

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.

Can we have multiple values for same key in HashMap?

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.


3 Answers

int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
like image 54
Tiemo Vorschütz Avatar answered Oct 13 '22 02:10

Tiemo Vorschütz


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
like image 34
Andreas Dolk Avatar answered Oct 13 '22 02:10

Andreas Dolk


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++;
  }
}
like image 28
kgiannakakis Avatar answered Oct 13 '22 02:10

kgiannakakis