Explain Codes LogoExplain Codes Logo

Treemap sort by value

java
custom-comparator
tree-map-sorting
java-8-streams
Anton ShumikhinbyAnton Shumikhin·Mar 8, 2025
TLDR

For a quick solution to sort a TreeMap by their values, follow these steps:

  1. Convert entrySet to a Stream
  2. Sort it using a custom Comparator derived from Map.Entry.getValue()
  3. Gather the sorted entries into a LinkedHashMap to uphold the order.

Here's how you do it in Java:

TreeMap<String, Integer> map = new TreeMap<>(); // Let's consider, map is already filled with data. Magic! Map<String, Integer> sorted = map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); // e1, the Houdini, survives when duplicates appear

Voila! You now have a LinkedHashMap that's sorted by the TreeMap’s values.

Busting TreeMap myths: Why it doesn’t sort by value

Ever wondered why a TreeMap doesn't naturally sort by value? The TreeMap class in Java, being a dutiful child of the SortedMap interface, keeps the order aligned to key comparisons. Sorting by value? That's a rebel act for TreeMap – it not only violates the SortedMap spec but also can introduce unexpected behavior.

How to break free: Sorting TreeMap by values

Custom Comparator: Time to compare apples to apples

This is where a custom Comparator comes to play! Create your custom Comparator to compare Map.Entry objects based on their values:

Comparator<Map.Entry<String, Integer>> valueComparator = (e1, e2) -> e1.getValue().compareTo(e2.getValue());

Advisory: Beware of the trap while dealing with Integer types. The '==' operator is a wolf in sheep clothing. Always use .equals() for Integer value equality.

The Immutable Guard: Handling TreeMap modification

Remember, treating the original TreeMap or SortedSet as a rag doll can cause complications. So, once you’ve converted the sorted entries into a LinkedHashMap, any subsequent modification should be made on this new map. If you still feel nostalgic about your old TreeMap, re-run the sorting operation after changes.

Considerations & Alternatives: Is there another way to Mordor?

The Stream Chalice: Leverage java streams

Been a java 8 user? You can now turn into a waterbender by manipulating streams to dictate the TreeMap value sorting process. Want to change the rules? Add Comparator.reverseOrder() and watch the magic happen!

Value sorting with Persistence: LinkedHashMap

Here's a hack: After sorting, use a LinkedHashMap to make insertion order persistent. Now that’s a core component to sustain the value-sorting intact!

Uniqueness Matter: Handling the Clones

Meet the clone troopers - duplicate values. While sorting by values, they might pose as hurdles in preserving uniqueness. In cases of duplicates, the merge function (e1, e2) -> e1 used in .collect(), helps to upkeep the first entry met. Now, that’s service towards the TreeMap's ordering contract!