How to sort a List in JAVA in a better way / the best way?
This is some notes written by Sheldon. I mainly focused on iOS programming but I also do JAVA and C# backend, you can find me with #iOSBySheldon in Github, Youtube, Facebook, etc.
High order functions with lambda is very easy in Swift [see article Here] but not that easy in languages like Objective-C or C++. In JAVA we can do it but since JAVA has too many versions, there are a lot different ways to do it, and there is always a better one you can choose.
Assuming we have a class like:
And we will have an list of Student to sort:
Sorting with Comparator
Comparator is the most classic one but also the one with the longest typing, basically we need to create a new Comparator for our sorting.
We can use Class function of Collection to sort:
Or directly use list instance function to sort:
Sorting with Lambda
Lambda is a better and more concise way to replace Comparator for developers. [Similar in Swift]
Sorting with Super Lambda Comparator
Note that for the first two ways, we are still comparing two things, but we can avoid comparing with:
Of course these are all sorting in the ascending order, if you need more complex condition to sort check the official document from Oracle Here.
:]
This is some notes written by Sheldon. I mainly focused on iOS programming but I also do JAVA and C# backend, you can find me with #iOSBySheldon in Github, Youtube, Facebook, etc.