How to sort an ArrayList in Java

To sort an ArrayList in Java, you can use the Collections.sort method.

Here is an example of how to sort an ArrayList of strings in ascending order:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

Collections.sort(list);

System.out.println(list);  // [apple, banana, cherry]

This will sort the ArrayList using the natural ordering of the elements, which is determined by the compareTo method of the Comparable interface.

If the elements of the ArrayList do not implement the Comparable interface, or if you want to use a different sort order, you can use the Collections.sort method that takes a comparator as an argument.

For example, to sort the ArrayList in descending order:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

Collections.sort(list, Collections.reverseOrder());

System.out.println(list);  // [cherry, banana, apple]

You can also use the sort method of the List interface, which is available in the java.util package in Java 8 and later.

For example:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

list.sort(Collections.reverseOrder());

System.out.println(list);  // [cherry, banana, apple]

Keep in mind that the sort method modifies the original list and does not create a new sorted list. If you want to preserve the original list, you can create a copy of the list and sort the copy instead.

For example:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

ArrayList<String> sortedList = new ArrayList<>(list);
sortedList.sort(Collections.reverseOrder());

System.out.println(sortedList);  // [cherry, banana, apple]
System.out.println(list);  // [apple, banana, cherry] (original list