簡體   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