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.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<Integer> numberList = Arrays.asList(numbers);

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

        // Convert the List back to array 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 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.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<Integer> 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 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 split a string?

Prior to Java 1.4 we use java.util.StringTokenizer class to split a tokenized string, for example a comma separated string. Starting from Java 1.4 and later the java.lang.String class introduce a String.split(String regex) method that simplify this process.

Below is a code snippet how to do it.

package org.kodejava.lang;

import java.util.Arrays;

public class StringSplit {
    public static void main(String[] args) {
        String data = "1,Diego Maradona,Footballer,Argentina";
        String[] items = data.split(",");

        // Iterates the array to print it out.
        for (String item : items) {
            System.out.println("item = " + item);
        }

        // Or simply use Arrays.toString() when print it out.
        System.out.println("item = " + Arrays.toString(items));
    }
}

The result of the code snippet:

item = 1
item = Diego Maradona
item = Footballer
item = Argentina
item = [1, Diego Maradona, Footballer, Argentina]

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]