Java - Compare Object (Comparable) (Collection Sort)

> Procedural Languages > Java

1 - About

Sort problem in java

3 - Compare

3.1 - String

"myString".compareTo("AnOtherString")

3.2 - Collection

In order to sort a collection, you need to compare each element of the collection.

3.2.1 - Comparable

To do this, you can implement the Comparable interface and use a sorted collection implementation.

public class Person implements Comparable<Person> {
    public int compareTo(Person o) {
        if (o.getName > this.getName) {
          return 1;
        } else {
          return 0;
        }
    }
}
 
Set myTreeSet = new TreeSet<Person>();
Advertising

3.2.2 - Sort

To sort a list collection, you can also pass an instance of a comparator as parameter to the sort() method:

Collections.sort(list, new ComparatorByValue());
// or
myCollection.sort((Comparator.comparing(MyObject::getMyProperty)))
 
// Natural Sort
Collections.sort(list);
Collections.reverse(list);

4 - Support

4.1 - Caused by: java.lang.ClassCastException: A class cannot be cast to java.lang.Comparable

When using a sorted collection, you will get this error of you are not implementing the comparable interface.

lang/java/comparable.txt · Last modified: 2018/03/09 07:09 by gerardnico