How do I sort items of an ArrayList?

This example shows you how we can sort items of an ArrayList using the Collections.sort() method. Beside accepting the list object to be sorted we can also pass a Comparator implementation to define the sorting behaviour such as sorting in descending or ascending order.

package org.kodejava.util;

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

public class ArrayListSortExample {
    public static void main(String[] args) {
        /*
         * Create a collections of colours
         */
        List<String> colours = new ArrayList<>();
        colours.add("red");
        colours.add("green");
        colours.add("blue");
        colours.add("yellow");
        colours.add("cyan");
        colours.add("white");
        colours.add("black");

        /*
         * We can sort items of a list using the Collections.sort() method.
         * We can also reverse the order of the sorting by passing the
         * Collections.reverseOrder() comparator.
         */
        Collections.sort(colours);
        System.out.println(Arrays.toString(colours.toArray()));

        colours.sort(Collections.reverseOrder());
        System.out.println(Arrays.toString(colours.toArray()));
    }
}

The code will output:

[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]

How do I sort array values in case-insensitive order?

By default, when sorting an arrays the value will be ordered in case-sensitive order. This example show you how to order it in case-insensitive order.

package org.kodejava.util;

import java.util.Arrays;

public class SortArrayCaseSensitivity {
    public static void main(String[] args) {
        String[] teams = new String[5];
        teams[0] = "Manchester United";
        teams[1] = "chelsea";
        teams[2] = "Arsenal";
        teams[3] = "liverpool";
        teams[4] = "EVERTON";

        // Sort array, by default it will be sorted in case-sensitive order.
        // [Arsenal, EVERTON, Manchester United, chelsea, liverpool]
        Arrays.sort(teams);
        System.out.println("Case sensitive  : " + Arrays.toString(teams));

        // Sort array in case-insensitive order
        // [Arsenal, chelsea, EVERTON, liverpool, Manchester United]
        Arrays.sort(teams, String.CASE_INSENSITIVE_ORDER);
        System.out.println("Case insensitive: " + Arrays.toString(teams));
    }
}

The result of the code snippet above:

Case sensitive  : [Arsenal, EVERTON, Manchester United, chelsea, liverpool]
Case insensitive: [Arsenal, chelsea, EVERTON, liverpool, Manchester United]

How do I sort array values in descending order?

Here you will find an example on how to sort the values of an array in ascending or descending order.

package org.kodejava.util;

import java.util.Arrays;
import java.util.Collections;

public class SortArrayWithOrder {
    public static void main(String[] args) {
        Integer[] points = new Integer[5];
        points[0] = 94;
        points[1] = 53;
        points[2] = 70;
        points[3] = 44;
        points[4] = 64;
        System.out.println("Original  : " + Arrays.toString(points));

        // Sort the points array, the default order is in ascending order.
        // [44, 53, 64, 70, 94]
        Arrays.sort(points);
        System.out.println("Ascending : " + Arrays.toString(points));

        // Sort the points array in descending order.
        // [94, 70, 64, 53, 44]
        Arrays.sort(points, Collections.reverseOrder());
        System.out.println("Descending: " + Arrays.toString(points));
    }
}

The result of the code snippet above are:

Original  : [94, 53, 70, 44, 64]
Ascending : [44, 53, 64, 70, 94]
Descending: [94, 70, 64, 53, 44]

How do I sort an array of objects?

In this example we are going to learn how to sort an array of objects. We start by using an array of String objects as can be seen in the code snippet below. We sort the contents of the array using Arrays.sort() method and print the sorted result. It was really simple.

String names[] = {"Bob", "Mallory", "Alice", "Carol"};
Arrays.sort(names);
System.out.println("Names = " + Arrays.toString(names));

Next, we will sort an array of our own object. It is a bit different compared to sorting an array of primitives. The first rule is we need our object to implements the Comparable interface. This interface have one contract we need to implement, the compareTo() contract.

The basic rule of the compareTo() method is to return 0 when objects value are equals, 1 if this object value is greater and -1 if this object value is smaller. In the Person class below we simply call the String object compareTo() method. See the Person class below for more details.

package org.kodejava.util.support;

public class Person implements Comparable<Person> {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public int compareTo(Person person) {
        return this.name.compareTo(person.name);
    }

    public String toString() {
        return name;
    }
}

In the snippet below we create four Person objects. We sort the Person object based on their name using the Arrays.sort() method and print out the array values.

Person persons[] = new Person[4];
persons[0] = new Person("Bob");
persons[1] = new Person("Mallory");
persons[2] = new Person("Alice");
persons[3] = new Person("Carol");
Arrays.sort(persons);
System.out.println("Persons = " + Arrays.toString(persons));

This is the main class where you can run all the snippet above:

package org.kodejava.util;

import org.kodejava.util.support.Person;

import java.util.Arrays;

public class ObjectSortExample {
    public static void main(String[] args) {
        String[] names = {"Bob", "Mallory", "Alice", "Carol"};
        Arrays.sort(names);
        System.out.println("Names = " + Arrays.toString(names));

        Person[] persons = new Person[4];
        persons[0] = new Person("Bob");
        persons[1] = new Person("Mallory");
        persons[2] = new Person("Alice");
        persons[3] = new Person("Carol");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Alice, Bob, Carol, Mallory]
Persons = [Alice, Bob, Carol, Mallory]

How do I sort elements of an array?

package org.kodejava.util;

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // An array of random numbers
        int[] numbers = {3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55};
        System.out.println("Before: " + Arrays.toString(numbers));

        // We need to sort these array elements into a correct order
        // from the smallest to the greatest. We will use the Arrays
        // class on java.utils package to do the sort. The sort
        // method of this class are overloaded, so they can take
        // other type of array as well such as byte[], long[],
        // float[], Object[].
        Arrays.sort(numbers);
        System.out.println("After : " + Arrays.toString(numbers));

        // We can also do the sort only for the specified range of
        // array elements.
        float[] money = {1.05f, 99.8f, 3f, 4.55f, 7.23f, 6.50f};
        Arrays.sort(money, 3, money.length);

        // Here we display the sort result, the first and the second
        // element of the array is not included in the sort process.
        System.out.println("Money : " + Arrays.toString(money));
    }
}

And here are the results:

Before: [3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55]
After : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Money : [1.05, 99.8, 3.0, 4.55, 6.5, 7.23]