To sort a List
in Java, you can use the sort
method of the List
interface and pass it a comparator that defines the sort order.
Here's an example of how you can do this:
List<String> list = Arrays.asList("apple", "banana", "cherry"); list.sort(Comparator.naturalOrder()); System.out.println(list);
This code will sort the elements of the List
in natural order (ascending order for strings) and print the sorted list to the console. The output will be:
[apple, banana, cherry]
You can customize the comparator to sort the elements based on different criteria, such as the length of the strings or the reverse order. For example, to sort the elements in descending order, you can use the reverseOrder
method of the Comparator
class:
List<String> list = Arrays.asList("apple", "banana", "cherry"); list.sort(Comparator.reverseOrder()); System.out.println(list);
This code will sort the elements in reverse order, and the output will be:
[cherry, banana, apple]
If the List
is already sorted and you just want to reverse the order of the elements, you can use the reverse
method of the Collections
class:
List<String> list = Arrays.asList("apple", "banana", "cherry"); Collections.reverse(list); System.out.println(list);
This code will reverse the order of the elements in the List
, and the output will be:
[cherry, banana, apple]