To sort elements in a List in Java, you can use the sort() method of the Collections class. This method sorts the List in ascending order by default, but you can also provide a Comparator object to specify a custom sorting order.
Here’s an example of how to use the sort() method to sort a List of integers:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
// create a List of integers
List<Integer> myList = new ArrayList<>();
myList.add(3);
myList.add(1);
myList.add(2);
// sort the List in ascending order
Collections.sort(myList);
System.out.println("Sorted List (ascending order): " + myList);
// sort the List in descending order using a custom Comparator
Collections.sort(myList, Collections.reverseOrder());
System.out.println("Sorted List (descending order): " + myList);
}
}
In this example, we create a List of integers called "myList" and add three elements to it. We then use the sort() method of the Collections class to sort the List in ascending order, and print out the sorted List using the println() method. We then sort the List in descending order by providing the reverseOrder() method of the Collections class as a Comparator, and again print out the sorted List.
The output of this program would be:
Sorted List (ascending order): [1, 2, 3]
Sorted List (descending order): [3, 2, 1]
As you can see, the sort() method sorts the List in ascending order by default, and we can provide a custom Comparator object to specify a different sorting order.
In summary, you can sort elements in a List in Java using the sort() method of the Collections class, and providing a Comparator object if you need a custom sorting order.