Java ArrayList Sort: Ascending and Descending Order

Learn to sort an ArrayList in Java using ArrayList.sort(), Collections.sort(), Comparator interface and Java 8 Streams. We can use the same methods for sorting in natural ordering as well as the reverse ordering of the elements stored in the ArrayList.

1. Different Ways to Sort an ArrayList

An ArrayList is an ordered and unsorted collection of elements and is part of the Java Collections framework, similar to other classes such as LinkedList or HashSet. By default, elements added in the ArrayList are stored in the order they are inserted.

When we need to sort the elements in the ArrayList, we can use the following techniques:

Sorting MethodWhen to Use
ArrayList.sort()For in-place sorting i.e., modifies the original arraylist.
Collection.sort() Internally uses ArrayList.sort() with no additional benefits.
Arraylist.stream.sorted()Does not modify the original list and returns a new sorted arraylist.
Provides a chance to perform other operations on the stream elements.

All the above methods, by default, sort the elements in natural order i.e. ascending order. We can use supply the custom ordering a Comparator instance for a custom order, such as Collections.reverseOrder() for the reverse order of the elements.

2. Enforcing the Sorting Order on Elements

For any object which needs to be stored and sorted in the natural order, without using a Comparator, we must implement the Comparable interface and write the logic to compare two instances. To demonstrate the sorting example, we will store the instances of Task.

Naturally, the sorting order sorts tasks by id field.

public record Task(long id, String name, boolean status)
    implements Comparable<Task> {

  @Override
  public int compareTo(Task other) {
    return Long.compare(other.id, this.id);
  }
}

For custom ordering, we can create Comparator instances having the appropriate sorting logic. For example, we can sort the tasks by the name field. Comparators are useful when the element (to be stored in the list) does not implement the Comparable interface.

Comparator<Task> nameSorter = Comparator.comparing(Task::name);
Comparator<E> reverseSorter = Comparator.reverseOrder();

Finally, for the demo, we are creating an arraylist with 5 tasks as follows:

//Create ArrayList
ArrayList<Task> arrayList = new ArrayList<>();

//Add items
arrayList.add(new Task(1, "One", true));
arrayList.add(new Task(2, "Two", false));
arrayList.add(new Task(3, "Three", true));
arrayList.add(new Task(4, "Four", false));
arrayList.add(new Task(5, "Five", true));

2. Sort ArrayList in Natural (Ascending) Order

The sort() is part of the List interface and has been implemented in ArrayList class since Java 8. It takes a Comparator instance used for enforcing the sorting order.

Note that ArrayList.sort() method does the in-place sorting i.e. it modifies the original list.

arrayList.sort(Comparator.naturalOrder());

The program output:

[ 
  Task[id=1, name=One, status=true], 
  Task[id=2, name=Two, status=false], 
  Task[id=3, name=Three, status=true], 
  Task[id=4, name=Four, status=false], 
  Task[id=5, name=Five, status=true]
]

To sort in reverse order, we can use the Comparator.reverseOrder() which returns a comparator that imposes the reverse of the natural ordering.

arrayList.sort(Comparator.reverseOrder());

The program output:

[ 
  Task[id=5, name=Five, status=true], 
  Task[id=4, name=Four, status=false], 
  Task[id=3, name=Three, status=true], 
  Task[id=2, name=Two, status=false], 
  Task[id=1, name=One, status=true]
]

Similarily, we can apply custom sorting using the custom comparator also.

arrayList.sort(Comparator.comparing(Task::name));

The program output prints the tasks in sorting order by names.

[ 
  Task[id=5, name=Five, status=true], 
  Task[id=4, name=Four, status=false], 
  Task[id=1, name=One, status=true], 
  Task[id=3, name=Three, status=true], 
  Task[id=2, name=Two, status=false]
]

3. Sort ArrayList using Collection.sort()

The Collection.sort() works very similar to List.sort(). In fact, internally, it uses the list.sort() method so it is recommended to use the List.sort() in place of Collections.sort().

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}

For reference purposes, let us see the code example of using the Collections.sort() method:

//Natural order
Collections.sort(arrayList);

//Reverse order
Collections.sort(arrayList, Comparator.reverseOrder());

//Custom order
Collections.sort(arrayList, Comparator.comparing(Task::name));

4. Sort ArrayList using Java 8 Streams

Using Java streams provides the opportunity to apply other intermediate operations on the sorted elements in the same statement.

Streams are even more useful when we do not want to modify the original arraylist, but rather temporarily sort the list and perform some operations on the sorted elements.

//Natural order
List<Task> sortedList = arrayList.stream().sorted().toList();

//Reverse order
List<Task> sortedList = arrayList.stream().sorted(Comparator.reverseOrder()).toList();

The following example combines the filter operation with the sorting operation on the stream elements. It selects only the active tasks, sorts the tasks by name, and collects the elements in a new List.

//Sorting with filtering
List<Task> list = arrayList.stream()
  .filter(t -> t.status())
  .sorted(Comparator.comparing(Task::name))
  .toList();

The program output:

[ Task[id=5, name=Five, status=true], 
  Task[id=1, name=One, status=true], 
  Task[id=3, name=Three, status=true]
]

5. Conclusion

In conclusion, we can say that sorting an arraylist is simple and easy in most cases. For specific cases, it is good to know the requirements and use the customized solution:

  • Implement Comparable interface for natural ordering, and use Comparator instances for custom and reverse ordering
  • Use List.sort() if we want to modify the original collection
  • Use Streams if we do not want to modify the original collection
  • Using Collections.sort() provides no benefit and thus can be avoided

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.