Sorting a List alphabetically using compareTo() method

北城余情 提交于 2019-12-01 18:10:21

As everyone else has mentioned, compareTo is part of the Comparable interface.

How you implement it depends on whether you want to order by surname or name first and if you want them sorted ascending order.

For example, if you want to order by surname first, in ascending order:

public class Person implements Comparable<Person> {
    // the parts of Person you already have would go here
    public int compareTo(Person person) {
        if (person == null) {
            return -1;
        }

        if (surname != null && person.getSur() == null) {
            return -1;
        } else if (surname == null && person.getSur() != null) {
            return 1;
        } else if (surname != null && person.getSur() != null) {
            int compare = surname.compareToIgnoreCase(person.getSur());
            if (compare != 0) {
                return compare;
            }
        }
        // Note that we did nothing if both surnames were null or equal

        if (name == null && person.getName() == null) {
            return 0;
        } else if (name != null && person.getName() == null) {
            return -1;
        } else if (name == null && person.getName() != null) {
            return 1;
        } else {
            return name.compareToIgnoreCase(person.getName());
        }
    }
}

(I didn't actually test this code)

This relies on String's implementation of compareToIgnoreCase.

Note that this also moves all null objects and objects with null names and surnames to the end of the list.

Having said all that, if you implement Comparable, you can make the Collections API do the work for you using sort.

If you find that you need multiple different sort methods for an object, you can create a set of Comparator objects to do the sorting instead.

You can make your Person class implement Comparable, and define the following method:

    public class Person implements Comparable<Person> {

       // Your previous code

       public int compareTo(Person other) {
          if (other == null) {
             // throw exception for example
          }
          return this.name.toLowerCase().compareTo(other.name.toLowerCase());
       }
    }

The Person class' signature should be like this:

public class Person implements Comparable<Person>

Add compareTo-method to Person class and use Collections.sort(personList) as starf suggested.

starf

Implement Comparable in your Person class.

Your compareTo() method would then be something like:

public int compareTo(Person other) {
    return name.compareTo(other.getName())
}

Then use Collections.sort(<your list of Person>);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!