Sorting an ArrayList Using Collections.sort()
in Java
In Java, we can easily sort an ArrayList
using the Collections.sort()
method, which is part of the java.util.Collections class. This method sorts the elements of the ArrayList in ascending order by default. If we need custom sorting, we can provide a comparator.
1. Sorting in Ascending Order
By default, Collections.sort()
sorts elements in natural order. This works well for elements that implement the Comparable
interface, such as String
, Integer
, and other wrapper classes.
Example:
import java.util.ArrayList;
import java.util.Collections;
public class SortExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Cherry");
System.out.println("Before sorting: " + list);
// Sorting in ascending order
Collections.sort(list);
System.out.println("After sorting: " + list);
}
}
Output:
Before sorting: [Banana, Apple, Cherry]
After sorting: [Apple, Banana, Cherry]
Explanation:
- The
Collections.sort(list)
method sorts theArrayList
in ascending alphabetical order becauseString
implements theComparable
interface.
2. Sorting in Descending Order
If we want to sort the ArrayList
in descending order, we can use the Collections.reverseOrder()
comparator.
Example:
import java.util.ArrayList;
import java.util.Collections;
public class DescendingSortExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Cherry");
System.out.println("Before sorting: " + list);
// Sorting in descending order
Collections.sort(list, Collections.reverseOrder());
System.out.println("After sorting: " + list);
}
}
Output:
Before sorting: [Banana, Apple, Cherry]
After sorting: [Cherry, Banana, Apple]
Explanation:
- The
Collections.sort(list, Collections.reverseOrder())
method sorts theArrayList
in descending order by using thereverseOrder()
comparator.
3. Sorting Using a Custom Comparator
For custom sorting, we can define a comparator that compares elements based on a custom rule. For instance, sorting strings by their length.
Example (Sorting by String Length):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class CustomSortExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Cherry");
System.out.println("Before sorting: " + list);
// Sorting by string length
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
return Integer.compare(str1.length(), str2.length());
}
});
System.out.println("After sorting by length: " + list);
}
}
Output:
Before sorting: [Banana, Apple, Cherry]
After sorting by length: [Apple, Cherry, Banana]
Explanation:
- The custom comparator compares the lengths of the strings. The shorter strings come first because
Integer.compare
(str1.length(), str2.length())
returns a negative value whenstr1
is shorter thanstr2
.
4. Sorting a List of Custom Objects
If we want to sort an ArrayList
of custom objects, your class must implement the Comparable
interface or you can use a Comparator
.
Example (Sorting by Age in a List of People):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (" + age + ")";
}
}
public class CustomObjectSortExample {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 30));
list.add(new Person("Charlie", 20));
System.out.println("Before sorting: " + list);
// Sorting by age (custom comparator)
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.age, p2.age); // Sorting by age
}
});
System.out.println("After sorting by age: " + list);
}
}
Output:
Before sorting: [Alice (25), Bob (30), Charlie (20)]
After sorting by age: [Charlie (20), Alice (25), Bob (30)]
Explanation:
- The
Person
class does not implementComparable
, so we use a custom comparator to sort by theage
field. The comparator compares the ages of twoPerson
objects.
Summary
Collections.sort(list)
: Sorts in natural (ascending) order if elements implementComparable
.Collections.sort(list, Collections.reverseOrder())
: Sorts in descending order.Custom Comparators: You can provide custom sorting logic using a comparator.
Sorting Custom Objects: Implement
Comparable
or use aComparator
to define how custom objects should be sorted.
These methods provide a flexible and easy way to sort ArrayLists
based on different criteria in Java.
To read how to use Comparator.comparing()
for Sorting - Visit: https://sdetinsider.hashnode.dev/sorting-arraylist-with-comparatorcomparing