计算有多少个哈希映射条目具有给定值

2022-09-03 03:55:12
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 的人数


答案 1

我只是在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}

答案 2

使用 Java 8:

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