Java - Compare Object (Comparable) (Collection Sort)

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

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

3.2.3 - Stream

  • Sort the timezone by raw offset

Arrays.stream(TimeZone.getAvailableIDs())
      .map(id->TimeZone.getTimeZone(id))
      .sorted(Comparator.comparing(TimeZone::getRawOffset))
      .forEach(tz-> System.out.println(+tz.getRawOffset()/1000/60/24+" - "+tz.getID()+" - "+tz.getDisplayName()));

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.


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap