1

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
5
  • Your code isn't right. Commented Jun 10, 2015 at 10:04
  • Please mention what do u mean by getName()? is that mentioned by "TEST1" or "Washington" Commented Jun 10, 2015 at 10:04
  • You are sorting the list alphabetically. TEST10 comes before TEST9 because of this - because 1 comes before 9. You have to modify the implementation of your compare() method to order the elements the way you want. Commented Jun 10, 2015 at 10:09
  • It will compare character by character, so it is printing TEST10 first and then TEST9 Commented Jun 10, 2015 at 10:09
  • Thank you all. Understood the concept. Commented Jun 11, 2015 at 5:08

3 Answers 3

2

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());
                    }
        });
Sign up to request clarification or add additional context in comments.

Comments

2

Alphabetically TEST10 comes before TEST9

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.