繁体   English   中英

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

[英]How to get count the same values from 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");

我的HashMap HM的值如下:

{ {x=48,y=80}=Red,{x=192,y=80}=Red,{x=192,y=320}=Blue,{x=336,y=560}=Blue }

这里,

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

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

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

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

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

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));
}

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

{"Red"=2, "Blue"=2}  // values are stored as Integer objects

你可以做到的唯一方法是迭代所有元素并计算出现次数:

for(String value: hm.values()) {
  if (value.equals(valueToCompare)) {
    count++;
  }
}
int countValue(String toMatch) {
  int count = 0;
  for (String v : HM.values()) {
    if (toMatch.equals(value)) {
      count++;
    }
  }
  return count;
}

此外,如果您只是存储两个值,则使用HashMap作为键可能有点过分。 内置Point使用int ,但使用float重新实现并不困难。

    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")) {

        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM