Click here to watch in Youtube : https://www.youtube.com/watch?v=AhMA81hEEH4&list=UUhwKlOVR041tngjerWxVccwCountry.java public class Country
{
private int countryId;
private String countryName;
public Country(int countryId, String countryName)
{
super();
this.countryId = countryId;
this.countryName = countryName;
}
public int getCountryId()
{
return countryId;
}
public void setCountryId(int countryId)
{
this.countryId = countryId;
}
public String getCountryName()
{
return countryName;
}
public void setCountryName(String countryName)
{
this.countryName = countryName;
}
}
CountrySortByNameComparator.java import java.util.Comparator;
public class CountrySortByNameComparator implements Comparator<Country>
{
/*
* This method has logic to arrange the country objects in descending order
* based on Country Name.
*/
@Override
public int compare(Country country1, Country country2)
{
System.out
.println("Compare method in CountrySortByNameComparator has been called"
+ "\nin order to arrange the country objects in descending order \nbased on Country Name.\n");
return country2.getCountryName().compareTo(country1.getCountryName());
}
}
CollectionsSortExample.java import java.util.ArrayList;
import java.util.Collections;
/*
* Example of sort(List<T> list, Comparator<? super T> c) method
*/
public class CollectionsSortExample
{
public static void main(String[] args)
{
Country india = new Country(1, "Bangladesh");
Country china = new Country(4, "China");
Country usa = new Country(3, "Australia");
Country srilanka = new Country(2, "Denmark");
ArrayList<Country> countryList = new ArrayList<Country>();
countryList.add(india);
countryList.add(china);
countryList.add(usa);
countryList.add(srilanka);
System.out.println("Before Sort : \n");
for (Country country : countryList)
{
System.out.println("Country Id: " + country.getCountryId() + " || "
+ "Country Name: " + country.getCountryName());
}
System.out.println("-------------------------------------------------");
/*
* Sorts the specified list according to the order induced by the
* specified comparator.
*/
Collections.sort(countryList, new CountrySortByNameComparator());
System.out.println("-------------------------------------------------");
System.out.println("\nAfter Sort : \n");
for (Country country : countryList)
{
System.out.println("Country Id: " + country.getCountryId() + " || "
+ "Country Name: " + country.getCountryName());
}
}
}