List collection multiple sorts

Write before:

Sometimes we need to sort the data when the query data is displayed on the front page, especially by multiple fields. There are a lot of troublesome codes. At this time, the features of java8 make it easy for us to sort the data.


Don't talk much, just go to the code.

public class Test {
    public static void main(String[] args) {
        List<DoubleSort> list = new ArrayList<DoubleSort>();
        list.add(new DoubleSort(0, "1",12));
        list.add(new DoubleSort(3, "2",15));
        list.add(new DoubleSort(2, "22",12));
        list.add(new DoubleSort(3, "11",17));
        list.add(new DoubleSort(3, "222",13));
        list.add(new DoubleSort(3, null,10));
// Simple sort by id Ascending sort
        list.forEach(e -> System.out.println(e.getId() + "," + e.getName()+","+e.getAge()));
// Secondary sort by id,age Ascending sort(First according to id Sort, id Same as age sort)
        list.forEach(e -> System.out.println(e.getId() + "," + e.getName()+","+e.getAge()));
// Sort multiple times by id,name,age Ascending sort(First according to id Sort, id Same as name Ascending sort(When name Yes null Value, sort first),Then? name Same as age Ascending sort)
        list.sort(Comparator.comparing(DoubleSort::getId).thenComparing(DoubleSort::getName, Comparator.nullsFirst(Comparator.naturalOrder())).thenComparing(DoubleSort::getAge));
        list.forEach(e -> System.out.println(e.getId() + "," + e.getName()));

The last sorting of the above code contains the processing method when the specified property is null. We can rank null first and call the corresponding method directly, which is very convenient and saves a lot of code!



Reference: ------java 8 secondary sorting and null pointer processing example

Tags: Java

Posted on Wed, 04 Dec 2019 08:56:34 -0500 by jacomus