我正在尝试弄清楚如何从HashMap中获得前10个值。我最初尝试使用TreeMap并让它按值排序,然后取前10个值,但这似乎不是一个选择,因为TreeMap是按键排序的。
我希望仍然能够知道哪些键具有最高的值,映射的K, V是String, Integer。
发布于 2013-03-15 23:52:55
也许您应该为存储在哈希图中的值对象实现Comparable接口。然后,您可以创建包含所有值的数组列表:
List<YourValueType> l = new ArrayList<YourValueType>(hashmap.values());
Collection.sort(l);
l = l.subList(0,10);问候
发布于 2013-03-15 23:57:40
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
map.put("A",99.5);
map.put("B",67.4);
map.put("C",67.4);
map.put("D",67.3);
System.out.println("unsorted map: "+map);
sorted_map.putAll(map);
System.out.println("results: "+sorted_map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}https://stackoverflow.com/questions/15436516
复制相似问题