How can I sort an Array List in Java?
To sort an Array List in Java, you can use the Collections. Sort method, which sorts the elements based on their natural ordering (for comparable types) or a custom comparator (for other types).
Example: import java.util.Array List;
import java.util.Collections;
public class Main (public static void main String args)
Array List<String> list = new ArrayList<>
list.add (“Orange”)
list.add (“Apple”)
list.add (“Banana”)
Collections.sort (list)
System.out.println (list)
This will sort the Array List in ascending order. If you want to sort it in descending order, you can use the Collections. Sort method with a custom comparator:
Collections. Sort (list, Collections. reverse Order
Alternatively, you can use the List. Sort method (available in Java 8 and later) to sort the Array List