【问题标题】:How to get count the same values from HashMap?如何从HashMap中获取相同的值?
【发布时间】:2011-07-04 07:02:09
【问题描述】:

如何从 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。 如果我给出的值等于“蓝色”,则意味着我想得到 count=2。

如何从 HashMAP HM 中获取相同的值?

【问题讨论】:

    标签: java android hashmap


    【解决方案1】:
    int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
    

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        【解决方案3】:

        唯一的方法是遍历所有元素并计算出现次数:

        for(String value: hm.values()) {
          if (value.equals(valueToCompare)) {
            count++;
          }
        }
        

        【讨论】:

        • "foreach" 不是 Java 关键字。
        【解决方案4】:
        int countValue(String toMatch) {
          int count = 0;
          for (String v : HM.values()) {
            if (toMatch.equals(value)) {
              count++;
            }
          }
          return count;
        }
        

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

        【讨论】:

          【解决方案5】:
              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")) {
          
                  }
              }
          

          【讨论】:

            猜你喜欢
            • 2013-08-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-25
            • 2014-06-14
            • 2011-09-15
            • 2013-04-21
            相关资源
            最近更新 更多