如何从HashMap中计算相同的值?

ios*_*per 8 java android hashmap

如何从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");
Run Code Online (Sandbox Code Playgroud)

我的HashMap HM的值如下:

{ {x=48,y=80}=Red,{x=192,y=80}=Red,{x=192,y=320}=Blue,{x=336,y=560}=Blue }
Run Code Online (Sandbox Code Playgroud)

这里,

我想计算HashMap HM中的相似值.

ie)如果我给值等于"红色"意味着我想得到count = 2.如果我给值等于"蓝色"意味着我想得到数= 2.

如何从HashMAP HM计算相同的值?

Tie*_*ütz 11

int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
Run Code Online (Sandbox Code Playgroud)


And*_*s_D 9

循环遍历条目集并将所有值放到第二个映射中,第一个映射值作为键,值将是计数:

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));
}
Run Code Online (Sandbox Code Playgroud)

您的示例的结果映射应如下所示:

{"Red"=2, "Blue"=2}  // values are stored as Integer objects
Run Code Online (Sandbox Code Playgroud)