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);
Run Code Online (Sandbox Code Playgroud)
如何返回多少人的价值1
Ada*_*dam 24
我只是对HashMap值使用Collections.frequency()方法,就像这样.
int count = Collections.frequency(party.values(), 1);
System.out.println(count);
===> 4
Run Code Online (Sandbox Code Playgroud)
或者一般解决方案,生成频率与数字的映射.
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}
Run Code Online (Sandbox Code Playgroud)
小智 7
使用 Java 8:
party.values().stream().filter(v -> v == 1).count();
Run Code Online (Sandbox Code Playgroud)
尝试这个:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10613 次 |
| 最近记录: |