Core Java

Sorting Java ArrayList in Ascending and Descending Order

ArrayList, which is part of the Java Collections Framework is a popular choice for storing and managing collections of data in Java programs. By default, when data is stored in an ArrayList, the insertion order is preserved. Sorting an ArrayList in ascending or descending order is a common operation when working with data. In this article, we will explore various ways to sort a Java ArrayList in both ascending and descending order, along with code examples.

1. Different Methods to Sort Elements in an ArrayList

We can sort an ArrayList of objects in Java using various methods. Listed below are some common approaches:

  • Using Collections.sort() method
  • Using the ArrayList.sort() method
  • Using Java 8 Stream API
  • Implementing the Comparable interface
  • Using Lambda expressions

2. Using the Collections.sort() Method

The Collections class provides two methods for sorting objects of an ArrayList class. They are:

  • sort(List<T> list): Method used to sort a list in ascending order based on the natural ordering of its elements.
  • sort(List<T> list, Comparator<? super T> c): This overloaded method allows us to sort a list using a custom Comparator to define the ordering of elements suitable for sorting objects based on criteria other than their natural ordering.

2.1 Sorting in Ascending Order using Collections.sort() Method

The following is an example of using the Collections.sort() method to sort an ArrayList in an ascending order:

public class ArrayListSorting {

    public static void main(String args[]) {
        
        //creating an ArrayList
        ArrayList<String> writers = new ArrayList<String>();
        writers.add("Thomas");
        writers.add("Charles");
        writers.add("Chinua");
        writers.add("Jonathan");
        writers.add("Daniel");
        
        System.out.println("Before Sorting: " + writers);
        
        //Use the Collections.sort() method to sort the ArrayList in ascending order.
        Collections.sort(writers);
        
        System.out.println("After Sorting: " + writers);
    }
}

In the above example, we start by creating an ArrayList of 5 Strings. We then use the Collections.sort() method to sort the list in ascending order.

The output from running the above code is:

Fig 1: Sorting Java ArrayList in Ascending Order using Collections.sort() method
Fig 1: Sorting Java ArrayList in Ascending Order using Collections.sort() method

2.2 Sorting in Descending Order

To sort an ArrayList in descending order using the Collections.sort() method, we can create a custom comparator and pass it as an argument to the Collections.sort() method like this:

public class ArrayListReverseOrder {

    public static void main(String[] args) {
        //create an ArrayList
        ArrayList<String> legumes = new ArrayList<String>();
        legumes.add("Lentils");
        legumes.add("Chickpeas");
        legumes.add("Soybeans");
        legumes.add("Peanuts");
        legumes.add("Beans");

        System.out.println("Before Sorting in Default Order: " + legumes);
        //sort ArrayList in descending order
        Collections.sort(legumes, new ReverseComparator());
        System.out.println("After Sorting in Descending Order: " + legumes);
    }
}

class ReverseComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        return s2.compareTo(s1);
    }
}

In the above code, we create an ArrayList with our data. We also create a custom comparator class named ReverseComparator. This comparator class is used to compare elements in reverse order, sorting them in descending order. We then sort our ArrayList using the custom comparator.

The output from running the above code is

Before Sorting in Default Order: [Lentils, Chickpeas, Soybeans, Peanuts, Beans]
After Sorting in Descending Order: [Soybeans, Peanuts, Lentils, Chickpeas, Beans]

3. Using ArrayList.sort() Method

Starting from Java 8 and beyond, we can use the ArrayList.sort() method with Comparator.naturalOrder() to sort elements in an ArrayList in their natural order in Java like this:

public class ArrayListSortExample {

    public static void main(String[] args) {
       
        // Create an ArrayList of strings
        ArrayList<String> legumes = new ArrayList<>();

        // Add elements to the ArrayList
        legumes.add("Lentils");
        legumes.add("Chickpeas");
        legumes.add("Soybeans");
        legumes.add("Peanuts");
        legumes.add("Beans");
        
        System.out.println("Before Sorting: " + legumes);
        
        // Use the ArrayList.sort() method with naturalOrder
        legumes.sort(Comparator.naturalOrder());
        
        System.out.println("After Sorting: " + legumes);
             
    }
}

In this example, we created an ArrayList of strings and used Comparator.naturalOrder() as the argument for the sort() method to sort the elements in ascending order. When we run the code, we get the following output:

Before Sorting: [Lentils, Chickpeas, Soybeans, Peanuts, Beans]
After Sorting: [Beans, Chickpeas, Lentils, Peanuts, Soybeans]

If we want to sort the ArrayList in descending order, we can update the above code and use the Collections.reverseOrder() comparator like this:

        //sorting an ArrayList in descending order
        legumes.sort(Comparator.reverseOrder());
        
        System.out.println("Reverse Sorting: " + legumes);

This will sort the elements in the ArrayList in reverse order (descending order). The output from running the updated code is:

Reverse Sorting: [Soybeans, Peanuts, Lentils, Chickpeas, Beans]

4. Sort ArrayList Utilizing Java Streams (Java 8+)

We can use Java 8 streams to sort an ArrayList in both ascending and descending order by using the stream() method to convert the ArrayList into a stream, and then using the sorted() method to sort the elements, and finally collect the sorted elements back into a list.

Below is an example of sorting an ArrayList in ascending and descending order using Java Streams:


public class ArrayListSortWithStreams {

       public static void main(String[] args) {
        // Create an ArrayList of Strings
        List alphabets = new ArrayList();
        alphabets.add("G");
        alphabets.add("A");
        alphabets.add("T");
        alphabets.add("W");
        alphabets.add("Y");

        // Sorting in ascending order using Java 8 streams
        List ascendingSorted = alphabets.stream()
                .sorted()
                .collect(Collectors.toList());

        // Sorting in descending order using Java 8 streams
        List descendingSorted = alphabets.stream()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.toList());

        // Display the results
        System.out.println("Ascending order: " + ascendingSorted);
        System.out.println("Descending order: " + descendingSorted);
    }
}

In the code above, We create an ArrayList called alphabets containing some String values.

To sort the list in ascending order, we use the sorted() method directly on the stream.

To sort the list in descending order, we use the sorted(Collections.reverseOrder()) method.

The collect(Collectors.toList()) method is used to collect the elements back into a new List after sorting.

When you run the code, we will see the ArrayList sorted in both ascending and descending order as shown in the output below:

Ascending order: [A, G, T, W, Y]
Descending order: [Y, W, T, G, A]

5. Using the Comparable Interface to Sort Custom Objects

We can use the Comparable interface to sort an ArrayList of objects in both ascending and descending order. We need to make sure our class implements the Comparable interface and overrides the compareTo() method.

First, let’s create a class named Person that implements the Comparable<person> interface, and overrides the compareTo() method in our custom class like this:

class Person implements Comparable {

    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Person otherPerson) {
        return this.name.compareTo(otherPerson.getName());
    }

    @Override
    public String toString() {
        return "Person{" + "name=" + name + ", age=" + age + '}';
    }

}

Next, let’s create an ArrayList of Person objects and sort it in ascending and descending order:

public class SortWithComparableInterface {

    public static void main(String[] args) {

        ArrayList<Person> people = new ArrayList<>();
        // Add some people to the list
        people.add(new Person("Thomas", 45));
        people.add(new Person("Charles", 50));
        people.add(new Person("Bob", 35));
        people.add(new Person("Jonathan", 60));
        people.add(new Person("Daniel", 12));

        // Sort in ascending order (natural order)
        Collections.sort(people);

        System.out.println("Ascending order:");
        for (Person person : people) {
            System.out.println(person);
        }

        // Sort in descending order by reversing the list
        Collections.reverse(people);

        System.out.println("\nDescending order:");
        for (Person person : people) {
            System.out.println(person);
        }
    }
}

In the above code, we first create an ArrayList of Person objects and then sort the List in ascending order using Collections.sort(people).

To sort the list in descending order, we use Collections.reverse(people) to reverse (in descending order) the list.

The compareTo method in the Person class determines the sorting order based on the name of the individuals.

When we run the application, we will get the following output:

Ascending order:
Person{name=Bob, age=35}
Person{name=Charles, age=50}
Person{name=Daniel, age=12}
Person{name=Jonathan, age=60}
Person{name=Thomas, age=45}

Descending order:
Person{name=Thomas, age=45}
Person{name=Jonathan, age=60}
Person{name=Daniel, age=12}
Person{name=Charles, age=50}
Person{name=Bob, age=35}

6. Using Lambda Expressions (Java 8 and later)

Using Java 8 onwards, you can use lambda expressions to sort a Java ArrayList of Strings in both ascending and descending order. The provided code snippet below illustrates the process of achieving this.

6.1 Sorting in Ascending Order using Lambda Expressions

public class SortArrayListLambda {

    public static void main(String[] args) {
        // Create an ArrayList of strings
        ArrayList<String> names = new ArrayList<>();
        names.add("Eva");
        names.add("Alicia"); 
        names.add("David");
        names.add("Charles");
        names.add("Bob");

        // Sort the ArrayList in ascending order using a lambda expression
        Collections.sort(names, (str1, str2) -> str1.compareTo(str2));

        // Print the sorted list
        System.out.println("Ascending Order: " + names);
    }
}

In this example, we use the Collections.sort() method along with a lambda expression (str1, str2) -> str1.compareTo(str2) to sort the ArrayList of Strings in ascending order.

The output is:

Ascending Order: [Alicia, Bob, Charles, David, Eva]

6.2 Sorting in Descending Order using Lambda Expressions

We can sort an ArrayList in descending order using Lambda expressions by updating our code with the following code snippet:

        // Sort the ArrayList in descending order using a lambda expression
        Collections.sort(names, (str1, str2) -> str2.compareTo(str1));

        // Print the sorted list
        System.out.println("Descending Order: " + names);

In this example, we use the lambda expression (str1, str2) -> str2.compareTo(str1) to reverse the order of comparison and sort the ArrayList of Strings in descending order.

7. Conclusion

Whether we are working with numerical data, strings, or custom objects, sorting in Java is a valuable skill to learn. We can choose from various methods, including the Comparable interface, lambda expressions, Java streams, using Collections.sort() method or ArrayList.sort() to achieve the desired sorting behavior needed in our application.

8. Download The Source Code

This was an example of Sorting Java ArrayList in Ascending and Descending Order.

Download
You can download the full source code of this example here: Sorting Java ArrayList in Ascending and Descending Order

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button