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...

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.sort(Comparator.comparing(DoubleSort::getId)); list.forEach(e -> System.out.println(e.getId() + "," + e.getName()+","+e.getAge())); System.out.println("----"); // Secondary sort by id,age Ascending sort(First according to id Sort, id Same as age sort) list.sort(Comparator.comparing(DoubleSort::getId).thenComparing(DoubleSort::getAge)); list.forEach(e -> System.out.println(e.getId() + "," + e.getName()+","+e.getAge())); System.out.println("----"); // 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:

https://blog.csdn.net/york_2016/article/details/80169467 ------java 8 secondary sorting and null pointer processing example

4 December 2019, 08:56 | Views: 9209

Add new comment

For adding a comment, please log in
or create account

0 comments