Error sorting list using Comparator

92 views Asked by At

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
3

There are 3 answers

0
Estimate On BEST ANSWER

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:

TEST1
TEST10
TEST9

You can try below code:

Collections.sort(countryList,new Comparator<Country>() {
                    public int compare(Country o1, Country o2) {
                        if (o1.getName().length() > o2.getName().length()) return 1;
                        if (o1.getName().length() < o2.getName().length()) return -1;

                        return o1.getName().compareTo(o2.getName());
                    }
        });
0
KgaboL On

Alphabetically TEST10 comes before TEST9

0
chengpohi On

The String compareTo use lexicographically to compare string, but your logic need compare the length of string:

Collections.sort(countryList,new Comparator<Country>() {
            public int compare(Country o1, Country o2) {
                if (o1.getName().length() > o2.getName().length()) return 1;
                if (o1.getName().length() < o2.getName().length()) return -1;

                return o1.getName().compareTo(o2.getName());
            }
});