Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top 10 values in hash map

I am trying to figure out how could I get the top 10 values from the HashMap. I was initially trying to use the TreeMap and have it sort by value and then take the first 10 values however it seems that that is not the option, as TreeMap sorts by key.

I want to still be able to know which keys have the highest values, the K, V of the map are String, Integer.

like image 625
Tohmas Avatar asked Mar 15 '13 15:03

Tohmas


1 Answers

Maybe you should implement the Comparable Interface to your value objects stored in the hashmap. Then you can create a array list of all values:

List<YourValueType> l = new ArrayList<YourValueType>(hashmap.values());
Collection.sort(l);
l = l.subList(0,10);

Regards

like image 140
sk2212 Avatar answered Oct 24 '22 16:10

sk2212