Core Java

Java sort ArrayList Example

1. Introduction

In this article we are going to look at the ArrayList class in Java. It is part of the java.util package. First though, in order to better understand the ArrayList class, we need to understand what an array is and how the two classes differ.

2. What is an Array?

Techterms.com offers a succinct definition of an array, which is not language specific:

An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organise data so that a related set of values can be easily sorted or searched.

https://techterms.com/definition/array

Arrays are an essential part of any developers toolkit. This is true for any programming language and the various collections they offer. Be it, tuples, lists or vectors, in Python, C# or Java. As coders we will always use these types of collections.

This however is an article about sorting an ArrayList in java. More specifically sorting an ArrayList in Java. So let’s look at doing just that.

3. The Java ArrayList class

The Oracle Java SE 8 API docs describes the ArrayList.class as a Resizable array implementation of the List interface. Unlike the java Array class, the ArrayList.class is resizable. Similar to the Vector class, but it is not synchronised.

The class has a capacity and uses this feature to handle resizing. Initial capacity can be set in the constructor. The default constructor creates an empty ArrayList with a capacity of ten. There are three constructors available as can be seen here:

ArrayList()
Constructs an empty list with an initial capacity of ten.

ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.

ArrayList(Collection collection)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

4. Sorting an ArrayList

Let’s create a basic ArrayList and then sort it.

JcgArrayListExample.class

package com.jcg.camel.example;

import java.util.ArrayList;

public class JcgArrayListExample {
	

	public static void main(String [] args) {
		
		//first let's create an ArrayList of Strings
		ArrayList verbList= new ArrayList();
		
		//next we add some verbs to our ArrayList
		verbList.add("Run");
		verbList.add("Jump");
		verbList.add("Sing");
		verbList.add("Dance");
		verbList.add("Laugh");
		
		//Now lets print the contents of the verbList
		System.out.println(verbList);
	
	}

}

When we run the above example it prints out the following:

[Run, Jump, Sing, Dance, Laugh]

Next we need to sort this arrayList. It should be as simple as calling sort() on the verbList we just created.

Java sort ArrayList
ArrayList sort method

Well while this method is available it’s not what we want as it requires the implementation of the Comparator interface. So yes, it could work, but we would have to write a lot more code and provide a comparable key for String as it does not have a default String implementation. There must be an simpler way.

You can read more about the Comparator here: https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

Enter the java java.util.Collections framework.

5. Using the Collections API for sorting

Let’s update our class to sort our ArrayList using Collections.

JcgArrayListExample.class

package com.jcg.camel.example;

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

public class JcgArrayListExample {	

	public static void main(String [] args) {
		
		//first let's create an ArrayList of Strings
		ArrayList verbList= new ArrayList();
		
		//next we add some verbs to our ArrayList
		verbList.add("Run");
		verbList.add("Jump");
		verbList.add("Sing");
		verbList.add("Dance");
		verbList.add("Laugh");
		
		//Now lets print the contents of the verbList
		System.out.println("The original unsorted ArrayList:" + verbList);
		
		
		//Now let's look at using the Collections class to sort our verbList
		Collections.sort(verbList);
		System.out.println("The sorted ArrayList:" + verbList);
		
		
	}

}

That is the point of the java.util.Collections framework, to make life easier for Java developers. There is an overview provided by Oracle which explicitly lists the advantages

The primary advantages of a collections framework are that it:

  • Reduces programming effort by providing data structures and algorithms so you don’t have to write them yourself.
  • Increases performance by providing high-performance implementations of data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be tuned by switching implementations.
  • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
  • Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs.
  • Reduces the effort required to design and implement APIs by not requiring you to produce ad hoc collections APIs.
  • Fosters software reuse by providing a standard interface for collections and algorithms with which to manipulate them.

Here is the link: https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html

6. Java sort ArrayList – Conclusion

This example showed us how to do basic sorting of an ArrayList in Java using the Collections API. The API is continually being updated as Java evolves as a language. Bringing with it more functionality and better operability among other things. I assure you a little bit of time spent reading up on this wonderful framework will save you a lot of time further down the line.

7. Download the Source Code

Download
You can download the full source code of this example here:
Java sort ArrayList Example

Ed de Jongh

Ed has worked in the IT industry for over 20 years, gaining experience in programming, architecture and design. As a seasoned Solution Architect, he is passionate about advancing simplicity and elegance. In addition to solution design, he is also involved in development and integration. Outside of the office, enjoys anything on two wheels and being a dad.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button