To sort a list in Java, you can use the Collections.sort()
method for ascending order and the Collections.sort()
method with a comparator for descending order. These methods are part of the java.util.Collections class.
In this example,
numbers
with integer values using the Arrays.asList()
method.Collections.sort()
method to sort the list in ascending order.Collections.sort()
method sorts the elements in natural order.System.out.println()
.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(numbers);
System.out.println("Sorted list in ascending order: " + numbers);
}
}
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
numbers
with integer values using the Arrays.asList()
method.Collections.sort()
method with Collections.reverseOrder()
to sort the list in descending order.Collections.reverseOrder()
method returns a comparator that sorts the elements in reverse natural order.System.out.println()
.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("Sorted list in descending order: " + numbers);
}
}
Sorted list in descending order: [8, 5, 3, 2, 1]
In this tutorial, we learned How to Sort a List in Java language with well detailed examples.