I have a list of objects. Each object contains a String
and a Date
(amongst others).
I want to first sort by the String
and then by the Date
.
How could this be done in the cleanest way possible?
Thanks!
Krt_Malta
The sort() callback function usually receives two arguments, say a and b, which are nothing but two elements of the array on which sort() was called and the callback function runs for each possible pair of elements of the array.
To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
With Java 8, this is really easy. Given
class MyClass {
String getString() { ... }
Date getDate() { ... }
}
You can easily sort a list as follows:
List<MyClass> list = ...
list.sort(Comparator.comparing(MyClass::getString).thenComparing(MyClass::getDate));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With