Signup/Sign In
PUBLISHED ON: JANUARY 27, 2021

How to sort ArrayList in Java

In this post, we are going to sort an ArrayList in Java. ArrayList is a class that is an implementation of List interface and used to store data.

Sorting is one of the fundamental operations of data that we use in day to day programming.

To sort an ArrayList there are several ways such as using sort() method of List or sort() method of Collections class or sorted() method of stream API.

We can use any of these sorting techniques based on the requirement like if we are working with stream then sorted() method will be helpful to get a sorted ArrayList.

Time for an Example:

Let's create an example to sort an ArrayList. Here we are using the sort() method that requires comparator argument and sorts the specified list.

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

public class Main {
	public static void main(String[] args){
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(1030);
		arrList.add(1020);
		arrList.add(1010);
		arrList.add(1040);
		System.out.println(arrList);
		// Sorting ArrayList
		arrList.sort(Comparator.comparing( Integer::new ));
		System.out.println("After Sorting:");
		System.out.println(arrList);
	}
}


[1030, 1020, 1010, 1040]
After Sorting:
[1010, 1020, 1030, 1040]

Example:

Let's create another example to sort an ArrayList. Here, we are using sort() method of Collections class that takes an argument and sort the list.

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

public class Main {
	public static void main(String[] args){
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(1030);
		arrList.add(1020);
		arrList.add(1010);
		arrList.add(1040);
		System.out.println(arrList);
		// Sorting ArrayList
		Collections.sort(arrList);
		System.out.println("After Sorting:");
		System.out.println(arrList);
	}
}


[1030, 1020, 1010, 1040]
After Sorting:
[1010, 1020, 1030, 1040]

Example: Java 8

If you are working on Java 8 or higher version then you can take advantage of stream API to sort an ArrayList. Here, we are using the sorted() method of the stream that helps to sort stream elements.

import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args){
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(1030);
		arrList.add(1020);
		arrList.add(1010);
		arrList.add(1040);
		System.out.println(arrList);
		// Sorting ArrayList
		arrList = (ArrayList<Integer>)arrList.stream().sorted().collect(Collectors.toList());
		System.out.println("After Sorting:");
		System.out.println(arrList);
	}
}


[1030, 1020, 1010, 1040]
After Sorting:
[1010, 1020, 1030, 1040]



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.