Monday, April 29, 2019

Sort Element of Tree using non natural sorting algorithm

By default TreeMap store element in default natural sorting of element. But if you want to store element other than default natural sorting order than you need to provide your own Comparator.
Java TreeMap class provide following Constructor for this  purpose.

TreeMap(Comparator<? super k> comparator).

Following example use String as key. As you know String class implements Comparable interface and define its compareTo(String o) method. String class sort element in ascending order(dictionary order).

In the first version of example i commented Comparator implementation.

TreeMap Program without Comparator   

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

public class TreeMapComparator {

public static void main(String[] args) {
TreeMap<String, String> cityMap = new TreeMap<>(/*
* new Comparator<String>() {
*
* @Override public int compare(String o1, String o2) { return
* o2.compareTo(o1);
*
* }
*
* }
*/);
cityMap.put("DL", "Delhi");
cityMap.put("BOM","Mumbai");
cityMap.put("UP","Uttar Pradesh");
cityMap.put("UK", "UttaraKhand");
cityMap.entrySet().stream().forEach(System.out::println);
}
}

output
BOM=Mumbai
DL=Delhi
UK=UttaraKhand
UP=Uttar Pradesh

TreeMap example with Comparator

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

public class TreeMapComparator {

public static void main(String[] args) {
TreeMap<String,String> cityMap=new TreeMap<>(new Comparator<String>() {

@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
cityMap.put("DL", "Delhi");
cityMap.put("BOM","Mumbai");
cityMap.put("UP","Uttar Pradesh");
cityMap.put("UK", "UttaraKhand");
cityMap.entrySet().stream().forEach(System.out::println);
}
}

output 

UP=Uttar Pradesh
UK=UttaraKhand
DL=Delhi
BOM=Mumbai


From the output of both program you can clearly understood 

No comments:

Post a Comment