java 计算有多少 HashMap 条目具有给定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12226130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count how many HashMap entries have a given value
提问by user1621988
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);
How can I return a number of how many peoplehas the value 1
我怎样才能返回一个数字的多少人的值为1
回答by Adam
I'd just use the Collections.frequency() method on the HashMap values, like this.
我只是在 HashMap 值上使用 Collections.frequency() 方法,就像这样。
int count = Collections.frequency(party.values(), 1);
System.out.println(count);
===> 4
Or the general solution, generate a map of frequency against number.
或者一般的解决方案,生成一个频率与数字的映射。
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}
回答by alfasin
Try this:
试试这个:
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);
回答by Sathish
you can use this
你可以用这个
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());
}
回答by codeDisaster
Try out this library for a lot of such group by function http://code.google.com/p/lambdaj/wiki/LambdajFeatures
通过功能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());
You might need to import these maven dependencies
您可能需要导入这些 Maven 依赖项
<dependency> <groupId>com.googlecode.lambdaj</groupId> <artifactId>lambdaj</artifactId> <version>2.3.3</version>
<dependency> <groupId>com.googlecode.lambdaj</groupId> <artifactId>lambdaj</artifactId> <version>2.3.3</version>
and hamcrest matchers for
和 hamcrest 匹配器
equalTo(1)
回答by ZiadM
Using Java 8:
使用 Java 8:
party.values().stream().filter(v -> v == 1).count();