How to sort a List/ArrayList?
To arrange your troops (elements of List
) in Java, instantly resort to Collections.sort(list)
. For ascending reconnaissance, use this; else for custom war strategy include a Comparator
: Collections.sort(list, Comparator.reverseOrder())
. Java 8 gives us Gandalf's staff (list.sort(Comparator.naturalOrder()
) for ascending, or list.sort(Comparator.reverseOrder())
for descending order.
For classic sorting, blindly go for Collections.sort()
, but for readability and flexible codes, List.sort()
with Java 8+ brings the magic.
Ease your troubles with Comparators
With Comparators, define your sorting logic to ease your troubles. These can either be traditional anonymous classes or extremely simple lambda expressions:
For Java 8 stream fans, the sorted()
function makes sorting relaxing and effortless:
Match up with the perfect Comparator
Java confers the ability of using ternary operator shorthands along with type inference, helping you write custom comparators to run for the specific landmark:
Lambdas and method references: Ease your burden
With lambda expressions and method references, retain your code's brevity and readability, especially while implementing single-method interfaces like Comparator
:
Advanced Collections Sorting
Apply the Collections library to meet your complex sorting demands:
Sorting in descending order
For descending view of your list, sort it first and then reverse. The magic:
The power of Stream API
Incredibly powerful sorting methods await with the Stream API. In-line custom sorting is also possible with Comparator.comparing().reversed()
:
Non-destructive sorting is what Streams offer, so no worries about altering your original list.
Was this article helpful?