How do I reverse the order of array elements?

In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse() method. This method requires an argument with List type. Because of this we need to convert the array to a List type first. We can use the Arrays.asList() to do the conversion. And then we reverse it. To convert the List back to array we can use the Collection.toArray() method.

Let’s see the code snippet below:

package org.kodejava.example.util;

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

public class ArrayReverse {
    public static void main(String[] args) {
        // Creates an array of Integers and print it out.
        Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Arrays.toString(numbers) = " + Arrays.toString(numbers));

        // Convert the int arrays into a List.
        List numberList = Arrays.asList(numbers);

        // Reverse the order of the List.
        Collections.reverse(numberList);

        // Convert the List back to arrays of Integers
        // and print it out.
        numberList.toArray(numbers);
        System.out.println("Arrays.toString(numbers) = " + Arrays.toString(numbers));
    }
}

The output of the code snippet above is:

Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]

How do I sort string of numbers in ascending order?

In the following example we are going to sort a string containing the following numbers "2, 5, 9, 1, 10, 7, 4, 8" in ascending order so we will get the result of "1, 2, 4, 5, 7, 8, 9, 10".

package org.kodejava.example.util;

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

public class SortStringNumber {
    public static void main(String[] args) {
        // We have some string numbers separated by comma. First we
        // need to split it so we can get each individual number.
        String data = "2, 5, 9, 1, 10, 7, 4, 8";
        String[] numbers = data.split(",");

        // Convert the string numbers into Integer and placed it into
        // an array of Integer.
        Integer[] intValues = new Integer[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intValues[i] = Integer.parseInt(numbers[i].trim());
        }

        // Sort the number in ascending order using the
        // Collections.sort() method.
        Collections.sort(Arrays.asList(intValues));

        // Convert back the sorted number into string using the
        // StringBuilder object. Prints the sorted string numbers.
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < intValues.length; i++) {
            Integer intValue = intValues[i];
            builder.append(intValue);
            if (i < intValues.length - 1) {
                builder.append(", ");
            }
        }
        System.out.println("Before = " + data);
        System.out.println("After  = " + builder.toString());
    }
}

When we run the program we will get the following output:

Before = 2, 5, 9, 1, 10, 7, 4, 8
After  = 1, 2, 4, 5, 7, 8, 9, 10

How do I sort an Enumeration?

package org.kodejava.example.util;

import java.util.*;

public class EnumerationSort {
    public static void main(String[] args) {
        // Creates random data for sorting source. Will use java.util.Vector
        // to store the random integer generated.
        Random random = new Random();
        Vector<Integer> data = new Vector<>();
        for (int i = 0; i < 10; i++) {
            data.add(Math.abs(random.nextInt()));
        }

        // Get the enumeration from the vector object and convert it into
        // a java.util.List. Finally we sort the list using
        // Collections.sort() method.
        Enumeration<Integer> enumeration = data.elements();
        List<Integer> list = Collections.list(enumeration);
        Collections.sort(list);

        // Prints out all generated number after sorted.
        for (Integer number : list) {
            System.out.println("Number = " + number);
        }
    }
}

An example result of the code above is:

Number = 574156412
Number = 692265226
Number = 852855412
Number = 858413518
Number = 1272648602
Number = 1851829368
Number = 1960139525
Number = 2053222887
Number = 2055598873
Number = 2081007654

How do I sort LinkedList elements?

To sort the elements of LinkedList we can use the Collections.sort(List<T> list) static methods. The default order of the sorting is a descending order.

package org.kodejava.example.util;

import java.util.LinkedList;
import java.util.Collections;

public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("E");
        grades.add("C");
        grades.add("A");
        grades.add("F");
        grades.add("B");
        grades.add("D");

        System.out.println("Before sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        // Sort the elements of linked list based on its data
        // natural order.
        Collections.sort(grades);

        System.out.println("After sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

The result of the program are:

Before sorting:
===============
Grade = E
Grade = C
Grade = A
Grade = F
Grade = B
Grade = D
After sorting:
===============
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F

How do I reverse the order of LinkedList elements?

To reverse the order of LinkedList elements we can use the reverse(List<?> list) static method of java.util.Collections class. Here is the example:

package org.kodejava.example.util;

import java.util.LinkedList;
import java.util.Collections;

public class LinkedListReverseOrder {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");
        grades.add("F");

        System.out.println("Output in original order:");
        System.out.println("=========================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        // Reverse the element order in the linked list object.
        Collections.reverse(grades);

        System.out.println("Output in reverse order:");
        System.out.println("=========================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

Here is the output of the program:

Output in original order:
=========================
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F
Output in reverse order:
=========================
Grade = F
Grade = E
Grade = D
Grade = C
Grade = B
Grade = A

How do I search collection elements?

This examples use the Collections.binarySearch() to search an specified object inside a specified collections. Prior to calling the binarySearch() method we need to sort the elements of the collection. If the object is not sorted according to their natural order the search result will be undefined.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Collections;
import java.text.DateFormatSymbols;

public class CollectionSearch {
    public static void main(String[] args) {
        DateFormatSymbols dfs = new DateFormatSymbols();

        LinkedList<String> monthList = new LinkedList<>();
        monthList.addAll(Arrays.asList(dfs.getMonths()));

        // Sort the collection elements
        Collections.sort(monthList);
        System.out.println("Months = " + monthList);

        // Get the position of November inside the monthList. It returns a positive
        // value if the item found in the monthList.
        int index = Collections.binarySearch(monthList, "November");
        if (index > 0) {
            System.out.println("Found at index = " + index);
            System.out.println("Month = " + monthList.get(index));
        }
    }
}

The output of the code snippet above is below.

Months = [, April, August, December, February, January, July, June, March, May, November, October, September]
Found at index = 10
Month = November

How do I rotate elements of a collection?

This example demonstrate how to rotate the elements of a collection object. We can use the java.util.Collections class and call the rotate() method with the collection to rotate and the distance as the parameters.

package org.kodejava.example.util;

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

public class CollectionRotate {
    public static void main(String[] args) {
        List numbers = new ArrayList();

        // Add some items into the collection
        for (int i = 0; i < 25; i++) {
            numbers.add(i);
        }

        // Print the collection items        
        System.out.println(Arrays.toString(numbers.toArray()));

        // Rotates the elements in the collection by the 10.
        Collections.rotate(numbers, 10);

        // Print the rotated collection items
        System.out.println(Arrays.toString(numbers.toArray()));
    }
}

Here is the program result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

How do I sort strings using Collator class?

In this example we demonstrate how to use the java.text.Collator class to sort strings in language-specific order. Using the java.text.Collator class makes the string not just sorted by the ASCII code of their characters but it will follow the language natural order of the characters.

package org.kodejava.example.text;

import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Collections;
import java.text.Collator;

public class StringShortWithCollator {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Guava");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");
        fruits.add("Apple");

        // Define a collator for US English.
        Collator collator = Collator.getInstance(Locale.US);

        // Sort the list base on the collator
        Collections.sort(fruits, collator);

        for (String fruit : fruits) {
            System.out.println("Fruit = " + fruit);
        }
    }
}

The result of the code snippet above are:

Fruit = Apple
Fruit = Banana
Fruit = Guava
Fruit = Mango
Fruit = Orange

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.example.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()));

        Collections.sort(colours, 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 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.example.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]