Click here to watch in Youtube :https://www.youtube.com/watch?v=B4pwRRIaAaw&list=UUhwKlOVR041tngjerWxVccwAscendingCountryCodeComparator.java import java.util.Comparator;
public class AscendingCountryCodeComparator implements Comparator<String>
{
/*
* This method is used to arrange the CountryCodes in Ascending order.
*/
@Override
public int compare( String countryCode1, String countryCode2 )
{
System.out
.println("\nCompare method has been called in AscendingCountryCodeComparator,\nto arrange"
+ " the CountryCodes in ascending order : ");
System.out.println("countryCode1 = " + countryCode1
+ ", countryCode2 = " + countryCode2 + "\n");
return countryCode1.compareTo(countryCode2);
}
}
TreeMapExample.java import java.util.TreeMap;
/*
* Example of comparator() method.
*/
public class TreeMapExample
{
public static void main( String[] args )
{
AscendingCountryCodeComparator ascendingCountryCodeComparator = new AscendingCountryCodeComparator();
TreeMap<String, String> treeMap = new TreeMap<String, String>(
ascendingCountryCodeComparator);
/*
* Key is CountryCode - Value is CountryName
*/
System.out.println("Key:CN,Value:CHINA is going to be add in treeMap");
treeMap.put("CN", "CHINA");
System.out.println("Key:BE,Value:BELGIUM is going to be add in treeMap");
treeMap.put("BE", "BELGIUM");
System.out.println("Key:AF,Value:AFGHANISTAN is going to be add in treeMap");
treeMap.put("AF", "AFGHANISTAN");
System.out.println("Key:DK,Value:DENMARK is going to be add in treeMap");
treeMap.put("DK", "DENMARK");
System.out.println("treeMap : " + treeMap + "\n");
}
}
Output Key:CN,Value:CHINA is going to be add in treeMap
Compare method has been called in AscendingCountryCodeComparator,
to arrange the CountryCodes in ascending order :
countryCode1 = CN, countryCode2 = CN
Key:BE,Value:BELGIUM is going to be add in treeMap
Compare method has been called in AscendingCountryCodeComparator,
to arrange the CountryCodes in ascending order :
countryCode1 = BE, countryCode2 = CN
Key:AF,Value:AFGHANISTAN is going to be add in treeMap
Compare method has been called in AscendingCountryCodeComparator,
to arrange the CountryCodes in ascending order :
countryCode1 = AF, countryCode2 = CN
Compare method has been called in AscendingCountryCodeComparator,
to arrange the CountryCodes in ascending order :
countryCode1 = AF, countryCode2 = BE
Key:DK,Value:DENMARK is going to be add in treeMap
Compare method has been called in AscendingCountryCodeComparator,
to arrange the CountryCodes in ascending order :
countryCode1 = DK, countryCode2 = BE
Compare method has been called in AscendingCountryCodeComparator,
to arrange the CountryCodes in ascending order :
countryCode1 = DK, countryCode2 = CN
treeMap : {AF=AFGHANISTAN, BE=BELGIUM, CN=CHINA, DK=DENMARK}