About
Sort problem in java
Articles Related
Compare
String
"myString".compareTo("AnOtherString")
Collection
In order to sort a collection, you need to compare each element of the collection.
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>();
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);
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()));
Support
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.