Table of Contents
To sort a list of ArrayList in Java, you can use the Collections.sort() method or the List.sort() method. Both methods allow you to sort the elements of a list in ascending order, based on their natural order or using a custom comparator. Here are the steps to sort a list in Java:
Using Collections.sort()
1. Import the necessary classes:
import java.util.ArrayList; import java.util.Collections; import java.util.List;
2. Create an ArrayList and add elements to it:
List list = new ArrayList();
list.add("Apple");
list.add("Orange");
list.add("Banana");
3. Sort the list using the Collections.sort() method:
Collections.sort(list);
4. The list is now sorted in ascending order.
Related Article: Java Printf Method Tutorial
Using List.sort()
1. Import the necessary classes:
import java.util.ArrayList; import java.util.List;
2. Create an ArrayList and add elements to it:
List list = new ArrayList();
list.add("Apple");
list.add("Orange");
list.add("Banana");
3. Sort the list using the List.sort() method and a lambda expression:
list.sort((a, b) -> a.compareTo(b));
4. The list is now sorted in ascending order.
Sorting in Descending Order
To sort the list in descending order, you can use the Collections.reverseOrder() method as a comparator. Here's how:
1. Import the necessary classes:
import java.util.ArrayList; import java.util.Collections; import java.util.List;
2. Create an ArrayList and add elements to it:
List list = new ArrayList();
list.add("Apple");
list.add("Orange");
list.add("Banana");
3. Sort the list in descending order using the Collections.sort() method and Collections.reverseOrder() as a comparator:
Collections.sort(list, Collections.reverseOrder());
4. The list is now sorted in descending order.
Sorting Custom Objects
If you have a list of custom objects, you can implement the Comparable interface in your object class and override the compareTo() method to specify how the objects should be sorted. Here's an example:
public class Person implements Comparable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
}
Now, you can sort a list of Person objects based on their age:
List list = new ArrayList();
list.add(new Person("John", 25));
list.add(new Person("Alice", 30));
list.add(new Person("Bob", 20));
Collections.sort(list);
// The list is now sorted based on age in ascending order
Note: If you want to sort the list in descending order, you can modify the compareTo() method to return other.age - this.age.