Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list in Java using 2 criteria

Tags:

java

sorting

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

like image 854
Krt_Malta Avatar asked Apr 08 '11 12:04

Krt_Malta


People also ask

How do you sort an array by two conditions?

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.

How do you Multi sort in Java?

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.


1 Answers

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));
like image 75
Lukas Eder Avatar answered Oct 21 '22 20:10

Lukas Eder