Home >Java >javaTutorial >Detailed tutorial on sorting java list
This article provides a comprehensive guide to sorting Java lists. It explores different sorting algorithms and demonstrates how to sort lists based on single and multiple criteria, both in ascending and descending order. The article includes practic
Sorting a Java list involves arranging its elements in a specific order, either ascending or descending. The Collections.sort() method is primarily used for sorting lists in Java. To sort a list using this method, you can provide a Comparator as an argument. A Comparator defines the sorting order based on specific criteria.
To sort a Java list based on multiple criteria, you need to create a custom Comparator that considers all the criteria. For instance, if you have a list of objects with name and age attributes and want to sort the list by name first and then by age (in ascending order), you can create a Comparator as follows:
<code class="java">Comparator<Object> comparator = Comparator.comparing(Object::getName) .thenComparingInt(Object::getAge);</code>
Java provides various sorting algorithms:
To sort a Java list in ascending order:
To sort a Java list in descending order:
Example:
<code class="java">import java.util.Collections; import java.util.List; public class ListSorting { public static void main(String[] args) { List<Integer> numbers = List.of(5, 1, 4, 2, 3); // Sort in ascending order Collections.sort(numbers); System.out.println("Ascending order: " + numbers); // Sort in descending order Collections.sort(numbers, Collections.reverseOrder()); System.out.println("Descending order: " + numbers); } }</code>
The above is the detailed content of Detailed tutorial on sorting java list. For more information, please follow other related articles on the PHP Chinese website!