Order by; order by; order by; order by; Pretty quickly, I’ve summarized my usual sorting methods.

  • The traditional writing

So the thing is, now I’m going to sort this collection by age and ID all at once.

First I need a Comparator. In traditional writing I need an anonymous inner class to compare for me, so…… Compare the code to the sauce

So I solved my problem with the Comparator.

Compare is a Comparator. Compare takes arguments and returns as follows:

Negative (first small), 0 (equal), positive (first large)

  • Lambda compact code

Ok, that’s the traditional way, so I don’t want to write it that way, because I don’t think the code is neat enough, so I decided to use lambda expressions, so I’ll write it like this:

  • Adopt JDK8 package writing method

Ok, I streamlined the code with lambda, but I felt there was a more streamlined way to implement the functionality, so I wrote it like this.

list.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getId));
Copy the code

The advent of Lambda expressions greatly simplifies the writing of anonymous inner classes, such as new Runnable, New Comparator, and the less common New ActionListener, which can be elegantly expressed using Lambda expressions. The simplest of these Lambda expressions can be represented with comma-separated argument lists, -> symbols, and function blocks, which we can wrap in braces if a Lambda function block is a bit complicated. We can also display the specified parameter type, but with the type enclosed in parentheses.