【发布时间】:2015-07-29 10:29:05
【问题描述】:
我正在做一个项目,我需要从 HashMap 中找到至少 3 个三个值。我找到了一个找到最高值的代码。在这里。
public static <K, V extends Comparable<? super V>> List<Entry<K, V>>
findGreatest(Map<K, V> map, int n)
{
Comparator<? super Entry<K, V>> comparator =
new Comparator<Entry<K, V>>()
{
public int compare(Entry<K, V> e0, Entry<K, V> e1)
{
V v0 = e0.getValue();
V v1 = e1.getValue();
return v0.compareTo(v1);
}
};
PriorityQueue<Entry<K, V>> highest =
new PriorityQueue<Entry<K,V>>(n, comparator);
for (java.util.Map.Entry<K, V> entry : map.entrySet())
{
highest.offer(entry);
while (highest.size() > n)
{
highest.poll();
}
}
List<Entry<K, V>> result = new ArrayList<Map.Entry<K,V>>();
while (highest.size() > 0)
{
result.add(highest.poll());
}
return result;
}
如何修改它以找到最小值? 请在这里帮助我。 更新:抱歉我的错误,我希望从 HashMap
中找到最小值【问题讨论】:
标签: java hashmap comparator