Java – get the first 10 values in the hash map

I tried to figure out how to get the top 10 values from HashMap I initially tried to use treemap and sort by value, and then take the first 10 values, but it seems that this is not an option because treemap presses the key to sort

I think I can still know which keys have the highest value. The mapped K and V are string and integer

Solution

Perhaps you should implement the comparable interface as a value object stored in HashMap

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

to greet

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>