I have simple class
public class ActiveAlarm {
public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;
}
and List<ActiveAlarm>
con. How to sort in ascending order by timeStarted
, then by timeEnded
? Can anybody help? I know in C++ with generic algorithm and overload operator <, but I am new to Java.
Using
Comparator
For Example:
With Java 8 onwards, you can simply use lambda expression to represent Comparator instance.
You can call Collections.sort() and pass in a Comparator which you need to write to compare different properties of the object.
We can sort the list in one of two ways:
1. Using Comparator : When required to use the sort logic in multiple places If you want to use the sorting logic in a single place, then you can write an anonymous inner class as follows, or else extract the comparator and use it in multiple places
We can have null check for the properties, if we could have used 'Long' instead of 'long'.
2. Using Comparable(natural ordering): If sort algorithm always stick to one property: write a class that implements 'Comparable' and override 'compareTo' method as defined below
}
call sort method to sort based on natural ordering
Guava's ComparisonChain:
In java8+ this can be written in single line as follows,
collectionObjec.sort(comparator_lamda) or comparator.comparing(CollectionType::getterOfProperty)
code :
or
Since Java8 this can be done even cleaner using a combination of
Comparator
andLambda expressions
For Example: