Aldo Ziflaj

About Aldo Ziflaj

Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also a developer for Mozilla Albania team.

Java Collections Sort Example

In this example, I will show how to use the java.util.Collections class in order to perform sorting.

The Collections class consists of static methods that return or operate on collections, such as Lists, Maps, Sets, etc.

All the methods throw a NullPointerException if the collection(s) passed as a parameter is/are null.

ArraySortExample

Create a class named ArraySortExample with the following source code:

package com.javacodegeeks.example;

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

public class ArraySortExample {

	public static void main(String[] args) {
		ArrayList<Integer> randInts = new ArrayList<>();
		Random rnd = new Random();

		//generate 5 random ints for randInts
		for (int i=0;i<5;i++) {
			randInts.add(rnd.nextInt());
		}

		//show the unordered randInts
		printList(randInts);

		//sort the randInts ArrayList
		Collections.sort(randInts);

		//show the ordered randInts
		printList(randInts);
	}

	public static void printList(List<Integer> l) {
		System.out.print("[ ");
		for (int i=0;i<l.size();i++) {
			System.out.print(l.get(i)+" ");
		}
		System.out.println("]");
	}
}

My output is this (yours will be different):

[ -1503773474 -1286923903 1899281552 390130031 -706284752 ]
[ -1503773474 -1286923903 -706284752 390130031 1899281552 ]

I created an ArrayList and I filled it with 5 random integers, using java.util.Random class. Then, I used Collections.sort() to sort the integers in the ArrayList. I printed the ArrayList in both two stages: unsorted and sorted, in order to see the result of Collections.sort() method.

BackwardSortExample

The same method, Collections.sort(), can be also used to sort in the other direction, i.e. from the greatest number to the smallest. This can be done by adding another parameter, a Comparator. See the example below:

package com.javacodegeeks.example;

import java.util.*;

public class BackwardSortExample {

	public static void main(String[] args) {
		ArrayList<Integer> randInts = new ArrayList<>();
		Random rnd = new Random();

		//generate 5 random ints for randInts
		for (int i=0;i<5;i++) {
			randInts.add(rnd.nextInt());
		}

		//show the unordered randInts
		printList(randInts);

		//sort the randInts ArrayList
		Collections.sort(randInts, new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				return (o2.intValue() > o1.intValue()) ? 1 : -1;
			}
		});

		//show the ordered randInts
		printList(randInts);
	}

	public static void printList(List<Integer> l) {
		System.out.print("[ ");
		for (int i=0;i<l.size();i++) {
			System.out.print(l.get(i)+" ");
		}
		System.out.println("]");
	}
}

My output is:

[ 1496339441 247557973 -557265969 -1655233986 674163918 ]
[ 1496339441 674163918 247557973 -557265969 -1655233986 ]

What changed in this example is the order of the sorting: this time in reverse. To do this, I passed another parameter into Collections.sort() method, a Comparator and overloaded its compare(T o1,T o2) method. This method tells to the Collections.sort() method how to sort the elements of the Collection that needs to be sorted.

Download Code

Download
You can download the full source code of this example here : ArraySortExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close