[英]How to get count the same values from 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");
The values of my HashMap HM are as follows: 我的HashMap HM的值如下:
{ {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. 我想计算HashMap HM中的相似值。
ie) if i give value equals to "Red" means i want to get count=2. ie)如果我给值等于“红色”意味着我想得到count = 2。 if i give value equals to "Blue" means i want to get count=2. 如果我给值等于“蓝色”意味着我想得到数= 2。
How to get count the same values from HashMAP HM? 如何从HashMAP HM计算相同的值?
int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
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
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++;
}
}
int countValue(String toMatch) {
int count = 0;
for (String v : HM.values()) {
if (toMatch.equals(value)) {
count++;
}
}
return count;
}
Also, it is probably overkill to use a HashMap
as the key if you are just storing two values. 此外,如果您只是存储两个值,则使用HashMap
作为键可能有点过分。 The built in Point
uses int
, but it would not be hard to re-implement with float
. 内置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.