我现在有一个TreeMap,它拥有8组,根据字符串按字母顺序排序。我基本上需要根据它们的值(整数)显示前5组。例如 treeMap可能如下所示:
{A = 5,B = 1,C = 10,D = 16,E = 7,F = 2,G = 11}
我需要打印出来:
D = 16,G = 11,C = 10,E = 7,A = 5
我认为我不能直接从树图中做到这一点,但我想知道是否有人知道。提前谢谢!
答案 0 :(得分:0)
不,显然不能仅仅使用TreeMap
作为TreeMap
按key
排序,而不是value
排序。
您可以考虑在维护原始MultiMap
的同时维护TreeMap
(例如来自Guava)(因此您有2个地图。您可以更好地将它们封装到虽然是新的类,你使用数字作为键,字符串作为值。通过使用MultiMap
支持的TreeMap
,找出编号最大的n
个条目应该是微不足道的。
答案 1 :(得分:0)
正如Adrian Shum所说,单凭TreeMap
无法做到这一点。
但是,如果你偏离TreeMap
,你可以sort by value using a custom comparator,迭代结果并打印前五个条目。 请注意,链接的答案按升序排序,因此您必须将比较顺序切换为降序排序。
按值降序排序(从上面链接的SO答案中获取和修改):
import java.util.*
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list =
new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>()
{
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list)
{
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
打印前五个条目:
import java.util.*
Map<String, Integer> treeMap = // init to {A = 5,B = 1,...}
Map<String, Integer sortedByValue = sortByValue(treeMap);
int i = 0;
for (Map.Entry<String, Integer> entry : sortedByValue.entrySet()) {
if (i < 5) {
System.out.println(entry.getKey() + " = " + entry.getValue());
i++;
}
else {
// no need to keep looping once after we have printed the top 5 entries
break;
}
}