TreeMap: Sorting a TreeMap by Values

Let's discuss how we can sort the TreeMap elements on the basis of values.

We have a TreeMap in which we need to store the stock data. The key is the company’s name, and value is the price of the stock of that company.

By default, when we store the Map’s stock data, it will be stored in sorted order by key. But we need to store the data such that it is sorted by value. This means that the first element will be the company with the lowest stock price, and the last element will be the company with the highest stock price.

We know that while creating a TreeMap object we can provide a Comparator implementation that will be used to sort the elements. We can write a Comparator implementation so that it sorts the elements based on values instead of keys.

The below example shows how we can sort the elements on the basis of values. We have created a Comparator implementation that compares the values for the two keys passed to it.

Please note that in the below implementation, we are returning 1 if both the values are the same. The reason for doing this is that if two values are the same, then the TreeMap will consider it as duplicate, and it will not insert the keys in the Map.

Get hands-on with 1200+ tech skills courses.