Write a Java program to sort keys in Tree Map by using comparator


This program demonstrates how to sort the keys of a TreeMap based on their natural order or custom order defined by the Comparator interface. In this program, a TreeMap is created with a custom comparator object called sort_key. This comparator object implements the Comparator interface with the compare method overridden to compare two strings in natural order using the compareTo method.

The TreeMap is then populated with five key-value pairs using the put method. When the TreeMap is printed using System.out.println(s1) , the keys are sorted based on the comparator object sort_key. Since the keys are strings, the natural order of the keys is used for sorting them in ascending order.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class SortKeys
{  
	public static void main(String args[])
	{  
		TreeMap<String,String> s1 = new TreeMap<String,String>(new sort_key());
		s1.put("101", "John");
		s1.put("102", "Joes");
		s1.put("103", "Smith");
		s1.put("104", "Charles");
		s1.put("105", "George");
		System.out.println(s1); 
	}
}
class sort_key implements Comparator<String>
{
	@Override
	public int compare(String str1, String str2)
	{
		return str1.compareTo(str2);
	}
}

Output

{101=John, 102=Joes, 103=Smith, 104=Charles, 105=George}

Example Programs