As Adrian Shum mentioned, there is no way to do it simply by using a TreeMap
.
However, if you're okay with straying away from TreeMap
, you can sort by value using a custom comparator, iterate over the results and print the first five entries. Note that the linked answer sorts ascending, so you will have to switch the order of comparison to sort descending.
Sort by value descending (taken and modified from the SO answer linked above):
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;
}
Print the first five entries:
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;
}
}