计算有多少HashMap条目具有给定值

时间:2012-09-01 08:18:21

标签: java hashmap key

public final static HashMap<String, Integer> party = new HashMap<String, Integer>();
party.put("Jan",1);
party.put("John",1);
party.put("Brian",1);
party.put("Dave",1);
party.put("David",2);

如何返回一些有多少人的值 1

5 个答案:

答案 0 :(得分:23)

我只是对HashMap值使用Collections.frequency()方法,就像这样。

int count = Collections.frequency(party.values(), 1);
System.out.println(count);
===> 4

或者一般解决方案,根据数字生成频率图。

Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (Integer c : party.values()) {
    int value = counts.get(c) == null ? 0 : counts.get(c);
    counts.put(c, value + 1);
}
System.out.println(counts);
==> {1=4, 2=1}

答案 1 :(得分:3)

试试这个:

int counter = 0;
Iterator it = party.entrySet().iterator();
while (it.hasNext()) {
  Map.Entry pairs = (Map.Entry)it.next();
  if(pairs.getValue() == 1){
    counter++; 
  }      
}
System.out.println("number of 1's: "+counter);

答案 2 :(得分:2)

你可以用这个

HashMap<String, Integer> party = new HashMap<String, Integer>();
party.put("Jan",1);
party.put("John",1);
party.put("Brian",1);
party.put("Dave",1);
party.put("David",2);

Set<Entry<String, Integer>> set = party.entrySet();
for (Entry<String, Integer> me : set) {
    if(me.getValue()==1)
    System.out.println(me.getKey() + " : " + me.getValue());
}

答案 3 :(得分:2)

按功能试用这个库 http://code.google.com/p/lambdaj/wiki/LambdajFeatures

HashMap<String, Integer> party = new HashMap<String, Integer>();
    party.put("Jan",1);
    party.put("John",1);
    party.put("Brian",1);
    party.put("Dave",1);
    party.put("David",2);
    List<Integer> list = filter(equalTo(1),party.values());
    System.out.println(list.size());

您可能需要导入这些maven依赖项

<dependency>
      <groupId>com.googlecode.lambdaj</groupId>
     <artifactId>lambdaj</artifactId>
    <version>2.3.3</version>
     

和hamcrest matchers for

equalTo(1)

答案 4 :(得分:1)

使用Java 8:

party.values().stream().filter(v -> v == 1).count();