How to sort a List/ArrayList?

To sort a List or ArrayList in Java, you can use the sort method of the Collections class from the java.util package. The sort method takes a List and sorts it in ascending order according to the natural ordering of its elements.

Here's an example of how you can use the sort method to sort an ArrayList:

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayList
    List<Integer> list = new ArrayList<>();
    list.add(3);
    list.add(1);
    list.add(2);

    // Sort the ArrayList
    Collections.sort(list);

    // Print the sorted ArrayList
    for (int i : list) {
      System.out.println(i);
    }
  }
}

This code will print the following output:

1
2
3

Note that the sort method only works if the elements in the List implement the Comparable interface. If the elements do not