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.
Either make
ActiveAlarm
implementComparable<ActiveAlarm>
or implementComparator<ActiveAlarm>
in a separate class. Then call:or
In general, it's a good idea to implement
Comparable<T>
if there's a single "natural" sort order... otherwise (if you happen to want to sort in a particular order, but might equally easily want a different one) it's better to implementComparator<T>
. This particular situation could go either way, to be honest... but I'd probably stick with the more flexibleComparator<T>
option.EDIT: Sample implementation:
JAVA 8 and Above Answer (Using Lambda Expressions)
In Java 8, Lambda expressions were introduced to make this even easier! Instead of creating a Comparator() object with all of it's scaffolding, you can simplify it as follows: (Using your object as an example)
or even shorter:
That one statement is equivalent to the following:
Think of Lambda expressions as only requiring you to put in the relevant parts of the code: the method signature and what gets returned.
Another part of your question was how to compare against multiple fields. To do that with Lambda expressions, you can use the
.thenComparing()
function to effectively combine two comparisons into one:The above code will sort the list first by
timeStarted
, and then bytimeEnded
(for those records that have the sametimeStarted
).One last note: It is easy to compare 'long' or 'int' primitives, you can just subtract one from the other. If you are comparing objects ('Long' or 'String'), I suggest you use their built-in comparison. Example:
EDIT: Thanks to Lukas Eder for pointing me to
.thenComparing()
function.That should give you a rough idea. Once that's done, you can call
Collections.sort()
on the list.In java you need to use the static
Collections.sort
method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.You can use
Collections.sort
and pass your ownComparator<ActiveAlarm>
As mentioned you can sort by:
Comparable
Comparator
toCollections.sort
If you do both, the
Comparable
will be ignored andComparator
will be used. This helps that the value objects has their own logicalComparable
which is most reasonable sort for your value object, while each individual use case has its own implementation.