How to sort TreeMap in descending order in Java

  • 15 June 2017
  • ADM

 

How to sort TreeMap in descending order in Java - images/logos/java.jpg

 

TreeMap is a collection structured that orders the objects ascending based on the key. If you want to order descending or if you need a custom order you need to write your own comparator. To do that the java.util.Comparator interface needs to be extended.

The bellow comparator will order descending the value based on the string keys.

class DescOrder implements Comparator<String> {

	@Override
	public int compare(String o1, String o2) {
	    return o2.compareTo(o1);
	}
}

Example

package com.admfactory.basic;

import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapSort {

    static class DescOrder implements Comparator<String> {

	@Override
	public int compare(String o1, String o2) {	    
	    return o2.compareTo(o1);
	}
    }

    public static void main(String[] args) {
        System.out.println("TreeMap Desc Order Example"); 
        System.out.println();

	TreeMap<String, String> map1 = new TreeMap<String, String>(new DescOrder());
	map1.put("A1", "A1");
	map1.put("A4", "A4");
	map1.put("A2", "A2");
	map1.put("A10", "A10");
	map1.put("A30", "A30");

	System.out.println(map1);
    }
}

Output

TreeMap Desc Order Example

{A4=A4, A30=A30, A2=A2, A10=A10, A1=A1}

As you can notice the output will order the TreeMap in descending order. The order is not exactly what I expected, but is correct as A4 is bigger than A3..... In order to 'fix' this and to put A30 as the first element, a small improvement to the comparator is needed.

class DescOrder implements Comparator<String> {

	@Override
	public int compare(String o1, String o2) {
	    if (o1.length() > o2.length())
		return -1;
	    return o2.compareTo(o1);
	}
    }

Now you can see that the order is different.

TreeMap Desc Order Example

{A30=A30, A10=A10, A4=A4, A2=A2, A1=A1}

 

References