How do I find specific elements or object in an array?

This example demonstrates how to find specific items in an array. We will use the org.apache.commons.lang3.ArrayUtils class. This class provides method called contains(Object[] array, Object objectToFind) method to check if an array contains the objectToFind in it.

We can also use the indexOf(Object[] array, Object objectToFind) method and the lastIndexOf(Object[] array, Object objectToFind) method to get the index of an array element where our objectToFind is located.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsIndexOfDemo {
    public static void main(String[] args) {
        String[] colors = { "Red", "Orange", "Yellow", "Green",
                "Blue", "Violet", "Orange", "Blue" };

        // Does the "colors" array contain the Blue color?
        boolean contains = ArrayUtils.contains(colors, "Blue");
        System.out.println("Contains Blue? " + contains);

        // Can you tell me the index of each color defined bellow?
        int indexOfYellow = ArrayUtils.indexOf(colors, "Yellow");
        System.out.println("indexOfYellow = " + indexOfYellow);

        int indexOfOrange = ArrayUtils.indexOf(colors, "Orange");
        System.out.println("indexOfOrange = " + indexOfOrange);

        int lastIndexOfOrange = ArrayUtils.lastIndexOf(colors, "Orange");
        System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
    }
}

Here are the results of the code above.

Contains Blue? true
indexOfYellow = 2
indexOfOrange = 1
lastIndexOfOrange = 6

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I use CompareToBuilder class?

This example show how we can use the CompareToBuilder class for automatically create an implementation of compareTo(Object o) method. Please remember, when you are implementing this method, you will also need to implement the equals(Object o) method consistently. This will make sure the behavior of your class is consistent in relation to collection sorting processes.

package org.kodejava.commons.lang.support;

import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class Fruit implements Comparable<Fruit> {
    private String name;
    private String colour;

    public Fruit(String name, String colour) {
        this.name = name;
        this.colour = colour;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Fruit fruit = (Fruit) o;

        return new EqualsBuilder()
                .append(name, fruit.name)
                .append(colour, fruit.colour)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(name)
                .append(colour)
                .toHashCode();
    }

    /*
     * Generating compareTo() method using CompareToBuilder class. For another
     * alternative way, we can also use the CompareToBuilder.reflectionCompare()
     * method to implement the compareTo() method.
     */
    public int compareTo(Fruit fruit) {
        return new CompareToBuilder()
                .append(this.name, fruit.name)
                .append(this.colour, fruit.colour)
                .toComparison();
    }
}
package org.kodejava.commons.lang;

import org.kodejava.commons.lang.support.Fruit;

public class CompareToBuilderDemo {
    public static void main(String[] args) {
        Fruit fruit1 = new Fruit("Orange", "Orange");
        Fruit fruit2 = new Fruit("Watermelon", "Red");

        if (fruit1.compareTo(fruit2) == 0) {
            System.out.printf("%s == %s%n", fruit1.getName(), fruit2.getName());
        } else {
            System.out.printf("%s != %s%n", fruit1.getName(), fruit2.getName());
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I use ReflectionToStringBuilder class?

Implementing toString() method sometimes can become a time-consuming process. If you have a class with a few fields, it might be alright. However, when you deal with a lot of fields, it will surely take some time to update this method every time a new field comes and goes.

Here comes the ReflectionToStringBuilder class that can help you to automate the process of implementing the toString() method. This class provides a static toString() method that takes at least a single parameter that refer to an object instance from where the string will be generated.

We can also format the result of the generated string. In the example below we create the to string method with a ToStringStyle.MULTI_LINE_STYLE and we can also output transients and static fields if we want, which by default omitted.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class ReflectionToStringDemo {
    public static final String KEY = "APP-KEY";

    private Integer id;
    private String name;
    private String description;
    private transient String secretKey;

    public ReflectionToStringDemo(Integer id, String name, String description,
                                  String secretKey) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.secretKey = secretKey;
    }

    public static void main(String[] args) {
        ReflectionToStringDemo demo = new ReflectionToStringDemo(1, "MANUTD",
                "Manchester United", "secret**");
        System.out.println("Demo = " + demo);
    }

    @Override
    public String toString() {
        // Generate toString including transient and static fields.
        return ReflectionToStringBuilder.toString(this,
                ToStringStyle.MULTI_LINE_STYLE, true, true);
    }
}

The output produced by the code snippet above is:

Demo = org.kodejava.example.commons.lang.ReflectionToStringDemo@452b3a41[
  id=1
  name=MANUTD
  description=Manchester United
  KEY=APP-KEY
  secretKey=secret**
]

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I convert an array of object to an array of primitive?

In the code example below we demonstrate the ArrayUtils.toPrimitive() method to convert an array of Integer object to an array of its primitive type. Besides converting an array of Integer objects, this method is overloaded to accept other types of object’s array.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayObjectToPrimitiveDemo {
    public static void main(String[] args) {
        // An array of Integer objects.
        Integer[] integers = {1, 2, 3, 5, 8, 13, 21, 34, 55};
        Boolean[] booleans = {Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE};

        // Convert and array of Integer objects into an array of type int.
        int[] ints = ArrayUtils.toPrimitive(integers);
        System.out.println(ArrayUtils.toString(ints));

        // Convert an array of Boolean objects into an array of type boolean.
        boolean[] bools = ArrayUtils.toPrimitive(booleans);
        System.out.println(ArrayUtils.toString(bools));
    }
}

The output of our code snippet:

{1,2,3,5,8,13,21,34,55}
{true,true,false,false}

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I convert an array to a Map?

This example uses the Apache Commons Lang’s ArrayUtils.toMap() method to convert a two-dimensional array into a Map object.

To convert a two-dimensional array into a Map object, each element of the two-dimensional array must be an array with at least two elements where the first element will be the key and the second element will be the value.

package org.kodejava.commons.lang;

import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayToMapExample {

    public static void main(String[] args) {
        // A two-dimensional array of country capital.
        String[][] countries = {{"United States", "Washington, D.C."},
                {"United Kingdom", "London"},
                {"Netherlands", "Amsterdam"},
                {"Japan", "Tokyo"},
                {"France", "Paris"}};

        // Convert an array to a Map.
        Map<Object, Object> capitals = ArrayUtils.toMap(countries);
        for (Object key : capitals.keySet()) {
            System.out.printf("%s is the capital of %s.%n", capitals.get(key), key);
        }
    }
}

The result of our code snippet:

London is the capital of United Kingdom.
Amsterdam is the capital of Netherlands.
Paris is the capital of France.
Washington, D.C. is the capital of United States.
Tokyo is the capital of Japan.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central