Sorting ArrayList in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to sort ArrayList in Java. Sorting is one of the fundamental operations of data manipulation in programming. There are several ways to sort an ArrayList like using sort() method of List, sort() method of Collections class or sorted() method of stream API. We will cover all of these techniques in this lab.

Import ArrayList and Comparator

We need to import ArrayList and Comparator before starting the code in our Java program.

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

Create an ArrayList

Create an ArrayList with some elements. Here, we have created an ArrayList of integers with four elements 1030, 1020, 1010, and 1040.

ArrayList<Integer> arrList = new ArrayList<>();
arrList.add(1030);
arrList.add(1020);
arrList.add(1010);
arrList.add(1040);

Sorting using sort() method of List

We can use the sort() method of List to sort an ArrayList. It requires a Comparator argument to compare the elements of the ArrayList with each other. Here, we have used the comparing() method of Comparator interface to compare the elements of the ArrayList. And finally, we have called the sort() method of the ArrayList to sort it.

arrList.sort(Comparator.comparing(Integer::new));

Display the Sorted ArrayList

After sorting the ArrayList, we can display the sorted elements to verify that it is sorted.

System.out.println(arrList);

Sorting using sort() method of Collections

We can also use the sort() method of the Collections class to sort an ArrayList. It works on the same principle as the sort() method of List but it takes an argument of the list to be sorted.

Collections.sort(arrList);

Display the Sorted ArrayList

After sorting the ArrayList using the sort() method of Collections, we can display the sorted elements to verify that it is sorted.

System.out.println(arrList);

Sorting using sorted() method of stream API

If we are working on Java 8 or higher version, we can use the sorted() method of stream API to sort an ArrayList. Here, we have used the sorted() method of the stream to sort an ArrayList and finally, we have converted the sorted stream to the ArrayList using the toList() method of Collectors class.

arrList = (ArrayList<Integer>)arrList.stream().sorted().collect(Collectors.toList());

Display the Sorted ArrayList

After sorting the ArrayList using the sorted() method of stream API, we can display the sorted elements to verify that it is sorted.

System.out.println(arrList);

Summary

Sorting an ArrayList is an important operation in programming. In this lab, we have learned how to sort an ArrayList using the sort() method of List, sort() method of Collections class, and the sorted() method of stream API. We also learned how to create an ArrayList, display the elements in the ArrayList, and sort them. We hope this lab helped you learn how to sort an ArrayList in Java.

Other Java Tutorials you may like