gpt4 book ai didi

java - 如何发现 HashMap 中哪个值出现次数最多?

转载 作者:行者123 更新时间:2023-11-29 10:15:04 24 4
gpt4 key购买 nike

Map<String,String> votes = new HashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");

我如何检索最常出现在上面的 HashMap 中的值,在本例中为“School”。我将不胜感激最有效和最清晰的方法。

最佳答案

一个更简单的解决方案是只查看值。

public static <E> E mostFrequentElement(Iterable<E> iterable) {
Map<E, Integer> freqMap = new HashMap<>();
E mostFreq = null;
int mostFreqCount = -1;
for (E e : iterable) {
Integer count = freqMap.get(e);
freqMap.put(e, count = (count == null ? 1 : count+1));
// maintain the most frequent in a single pass.
if (count > mostFreqCount) {
mostFreq = e;
mostFreqCount = count;
}
}
return mostFreq;
}

对于 map 你可以做

V v = mostFrequentElement(map.values());

关于java - 如何发现 HashMap 中哪个值出现次数最多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20173657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com