Search code examples
javacollectionstreeset

Custom String Length Comparator: what's my mistake?


I defined a custom comparator to sort the name(String) variable of my objects by length.

Here's the code from my person class:

class MyNameLengthCompare implements Comparator<Person> {

        @Override
        public int compare(Person a, Person b) {
            if(a.getName().length() > b.getName().length()) {
                return -1;
            } else if (a.getName().length() < b.getName().length()) {
                return 1;
            } else
                return 0;
        }

    }

Then in my main method I called Collections.sort(personList, new MyNameLengthCompare); and then I added it to my TreeSet myTreeSet.addAll(personList)

But its not sorting by length of name :(


Solution

  • You don't need to sort it before you add it to the tree set. The only thing that matters is whether or not the tree set has the comparator.