I am trying to sort list of objects based on my name property. So I created a comparator and i notice it is not getting sorted. Please advise if any error in using this.
List<Country> countryList = new ArrayList<Country>();
Country country1 = new Country("TEST1","Washington");
Country country2 = new Country ("TEST10", New Delhi");
Country country3= new Country ("TEST9", London");
countryList.add(country1);
countryList.add(country2);
Collections.sort(countryList,new Comparator<Country>() {
public int compare(Country o1, Country o2) {
return o1.getName().compareTo(o2.getName());
}
});
I am getting out put as which should be other way.
TEST1 : Washington
TEST10 : New Delhi
TEST9 : London
Expected is
TEST1 : Washington
TEST9 : London
TEST10 : New Delhi
You are trying to sort by Name here. But names are TEST1, TEST10 and TEST9. When you compare this, you will get the order alphabetically:
You can try below code: