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.
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
3Note that the sort method only works if the elements in the List implement the Comparable interface. If the elements do not implement Comparable, you can pass a Comparator to the sort method instead:
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Cherry");
// Sort using a Comparator
Collections.sort(list, Comparator.reverseOrder());
for (String s : list) {
System.out.println(s);
}
}
}This will print the elements in reverse alphabetical order:
Cherry
Banana
Apple