Home >Java >javaTutorial >How do I Sort Java Collections by Custom Fields?
You have a Java collection that you desire to sort by a field. Here's how you can accomplish this:
Using a Comparator
If your collection elements don't implement Comparable, you can utilize a Comparator to specify the sorting criteria:
Comparator<CustomObject> comparator = (left, right) -> left.getId() - right.getId(); Collections.sort(list, comparator); System.out.println(list);
Using Comparable Interface (Java 8 )
If your CustomObject implements Comparable, you can directly apply Collections.sort():
Collections.sort(list);
Advanced Sorting Options
For more convenient syntax in Java 8 , consider the following options:
Collections.sort(list, (left, right) -> left.getId() - right.getId()); list.sort((left, right) -> left.getId() - right.getId()); list.sort(Comparator.comparing(CustomObject::getId));
Remember, the initial code used for the comparator approach can be applied to Java 8 as well.
The above is the detailed content of How do I Sort Java Collections by Custom Fields?. For more information, please follow other related articles on the PHP Chinese website!