Java Sort ArrayList Integers

This tutorial will explain with real working Java code how to numerically sort a list of random numbers. We will use the ArrayList as the container to hold out random integers and the Collections class to sort them.


Create Random Integers

We start by creating an ArrayList object of type integers. Let’s use the Random class to generate 20 numbers between 0 and 1000 and store the random integers in our ArrayList.

//Create an empty array list to hold integers
ArrayList<Integer> intArrayList = new ArrayList<Integer>();
		
//How many random numbers to generate?
int numberOfRandoms = 20;
		
//Number will be between 0 and 1000
int upperBounds = 1000;
		
//Create instance of Random class
Random random = new Random();
		
//Genrate 20 randomw numbers between 0 and 1000
for(int x=0; x<numberOfRandoms; x++)
{
	intArrayList.add(random.nextInt(upperBounds));
}


Sort ArrayList Numerically

Using the Collections.sort() method, we can sort our list of numbers numerically from smallest to largest.

//Sort our ArrayList
Collections.sort(intArrayList);


Sort ArrayList Numerically Reverse

We can also sort the list of numbers in reverse order using the Collections.reverse() method starting from largest to smallest number.

//Sort our ArrayList in reverse order
Collections.reverse(intArrayList);


Complete Sample Source Code

Below is the full java source code to sort an ArrayList of integers in ascending order and then in descending order.

package com.jcd.java.tutorials;

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

public class JavaSortListNumbers 
{

	public static void main(String[] args) 
	{
		
		//Create an empty array list to hold integers
		ArrayList<Integer> intArrayList = new ArrayList<Integer>();
		
		//How many random numbers to generate?
		int numberOfRandoms = 20;
		
		//Number will be between 0 and 1000
		int upperBounds = 1000;
		
		//Create instance of Random class
		Random random = new Random();
		
		//Genrate 20 randomw numbers between 0 and 1000
		for(int x=0; x<numberOfRandoms; x++)
		{
			intArrayList.add(random.nextInt(upperBounds));
		}
		
		//Sort our ArrayList
		Collections.sort(intArrayList);
		
		for(int myRand : intArrayList) 
		{
			System.out.println(myRand);
		}
		
		//Sort our ArrayList in reverse order
		Collections.reverse(intArrayList);
		System.out.println("");
		
		for(int myRand : intArrayList) 
		{
			System.out.println(myRand);
		}
		
	}

}
45
50
89
125
250
400
418
543
577
623
647
685
709
713
713
740
786
818
908
974

974
908
818
786
740
713
713
709
685
647
623
577
543
418
400
250
125
89
50
45



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *