Monday, January 13, 2025
HomeProgrammingHow to Sort ArrayList in Java

How to Sort ArrayList in Java

In Java, you can sort an ArrayList using the Collections.sort() method or the ArrayList.sort() method. These approaches allow you to sort the list in ascending or descending order. Here’s how you can do it:

1. Sorting an ArrayList of Integers or Strings

For simple data types like integers or strings, sorting is straightforward:

Code Example:

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList of integers
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(1);
        numbers.add(4);
        numbers.add(3);

        // Sort the ArrayList in ascending order
        Collections.sort(numbers);
        System.out.println("Sorted in Ascending Order: " + numbers);

        // Sort the ArrayList in descending order
        Collections.sort(numbers, Collections.reverseOrder());
        System.out.println("Sorted in Descending Order: " + numbers);
    }
}

Output:

Sorted in Ascending Order: [1, 3, 4, 5]
Sorted in Descending Order: [5, 4, 3, 1]
  • Collections.sort(numbers) sorts the list in ascending order.
  • Collections.reverseOrder() sorts the list in descending order.
See also  SQL Update Query Using Joins

2. Sorting an ArrayList of Custom Objects

If you have an ArrayList of custom objects, you need to implement the Comparable interface or use a Comparator to define the sorting logic.

Example with Comparable:

import java.util.ArrayList;
import java.util.Collections;

// Define a class
class Student implements Comparable<Student> {
    String name;
    int age;

    // Constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Override the compareTo method to sort by age
    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Ascending order by age
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 22));
        students.add(new Student("Bob", 20));
        students.add(new Student("Charlie", 21));

        // Sort the students by age
        Collections.sort(students);
        System.out.println("Sorted by Age (Ascending): " + students);
    }
}

Output:

Sorted by Age (Ascending): [Bob (20), Charlie (21), Alice (22)]

Example with Comparator:

If you need multiple sorting criteria or don’t want to modify the original class, you can use a Comparator.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

// Define a class
class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 22));
        students.add(new Student("Bob", 20));
        students.add(new Student("Charlie", 21));

        // Sort by name
        students.sort(Comparator.comparing(student -> student.name));
        System.out.println("Sorted by Name: " + students);

        // Sort by age in descending order
        students.sort((s1, s2) -> s2.age - s1.age);
        System.out.println("Sorted by Age (Descending): " + students);
    }
}

Output:

Sorted by Name: [Alice (22), Bob (20), Charlie (21)]
Sorted by Age (Descending): [Alice (22), Charlie (21), Bob (20)]

3. Using ArrayList.sort() (Since Java 8)

The ArrayList.sort() method is another way to sort directly without using Collections.sort().

Example:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Mango");

        // Sort in ascending order
        fruits.sort(String::compareTo);
        System.out.println("Ascending: " + fruits);

        // Sort in descending order
        fruits.sort((f1, f2) -> f2.compareTo(f1));
        System.out.println("Descending: " + fruits);
    }
}

Output:

Ascending: [Apple, Banana, Mango]
Descending: [Mango, Banana, Apple]

Key Takeaways:

  • Use Collections.sort() for simplicity with ascending and descending orders.
  • Implement Comparable in your custom class if you want natural ordering.
  • Use Comparator for more flexible and multiple sorting criteria.
  • From Java 8 onwards, you can use ArrayList.sort() with lambda expressions for concise code.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x