简体   繁体   中英

Error sorting list using Comparator

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

按字母顺序排列的TEST10在TEST9之前

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());
                    }
        });

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());
            }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM