How do I format date and time using DateFormatUtils class?

The DateFormatUtils class help us to format date and time information. This class use an instance of org.apache.commons.lang.time.FastDateFormat class to format the date and time information. Compared to Java SimpleDateFormat, the FastDateFormat class is thread safe.

If you want to create a custom date format you can use the FastDateFormat class directly.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.DateFormatUtils;

import java.util.Date;

public class DateFormattingDemo {
    public static void main(String[] args) {
        Date today = new Date();

        // ISO8601 formatter for date-time without time zone.
        // The format used is yyyy-MM-dd'T'HH:mm:ss.
        String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);

        // ISO8601 formatter for date-time with time zone.
        // The format used is yyyy-MM-dd'T'HH:mm:ssZZ.
        timestamp = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);

        // The format used is EEE, dd MMM yyyy HH:mm: ss Z in US locale.
        timestamp = DateFormatUtils.SMTP_DATETIME_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);
    }
}

The result of the code snippet:

timestamp = 2017-05-12T22:45:59
timestamp = 2017-05-12T22:45:59+08:00
timestamp = Fri, 12 May 2017 22:45:59 +0800

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

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

This example demonstrate how to find specific items in array. We will use the org.apache.commons.lang.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.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

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

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

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

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

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

Here are the result of the code above.

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

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

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 implementing this method you will also need to implement the equals(Object o) method consistently. This will make sure the behavior of your class consistent in relation to collections sorting process.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.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 other
     * 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.example.commons.lang;

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

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

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, but when you deal with a many fields it will surely take some time to update this method every time a new fields come and go.

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.example.commons.lang;

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

public class ReflectionToStringDemo {
    private Integer id;
    private String name;
    private String description;
    public static final String KEY = "APP-KEY";
    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;
    }

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

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

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

How do I convert array of object to 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 array of Integer objects this method is overloaded to accept other types of object array.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.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 array of Integer objects into array of type int.
        int[] ints = ArrayUtils.toPrimitive(integers);
        System.out.println(ArrayUtils.toString(ints));

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

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

How do I convert an array to a Map?

This example use 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.example.commons.lang;

import java.util.Map;

import org.apache.commons.lang.ArrayUtils;

public class ArrayToMapExample {

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

        // Convert an array to a Map.
        Map 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

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

How do I reverse array elements order?

In this example we are going to use the ArraysUtils helper class from Apache Commons Lang library to reverse the order of array elements. The method to reverse the order of array elements is ArrayUtils.reverse() method.

The ArrayUtils.reverse() method is overloaded so we can reverse other types of array such as java.lang.Object, long, int, short, char, byte, double, float and boolean.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

public class ArrayReverseExample {

    public static void main(String[] args) {
        // Define colors array.
        String[] colors = {"Red", "Green", "Blue", "Cyan", "Yellow", "Magenta"};
        System.out.println(ArrayUtils.toString(colors));

        // Now we reverse the order of array elements. 
        ArrayUtils.reverse(colors);
        System.out.println(ArrayUtils.toString(colors));
    }
}

Here is the output of the code snippet above:

{Red,Green,Blue,Cyan,Yellow,Magenta}
{Magenta,Yellow,Cyan,Blue,Green,Red}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

How do I count word occurrences in a string?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class WordCountDemo {
    public static void main(String[] args) {
        // We have the source text we'll do the search on.
        String source = "From the download page, you can download the Java " +
            "Tutorials for browsing offline. Or you can just download " +
            "the examples.";
        // The word we want to count its occurrences
        String word = "you";

        // Using StringUtils.countMatches() method we can count the occurrences
        // frequency of a word/letter in the giver source of string.
        int wordFound = StringUtils.countMatches(source, word);

        // Print how many we have found the word
        System.out.println(wordFound + " occurrences of the word '" + word +
            "' was found in the text.");
    }
}

Here is the result of the code above.

2 occurrences of the word 'you' was found in the text.

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

How do I reverse a string, words or sentences?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class StringReverseDemo {
    public static void main(String[] args) {
        // We have an original string here that we'll need to reverse.
        String words = "The quick brown fox jumps over the lazy dog";

        // Using StringUtils.reverse we can reverse the string letter by letter.
        String reversed = StringUtils.reverse(words);

        // Now we want to reverse per word, we can use
        // StringUtils.reverseDelimited() method to do this.
        String delimitedReverse = StringUtils.reverseDelimited(words, ' ');

        // Print out the result
        System.out.println("Original: " + words);
        System.out.println("Reversed: " + reversed);
        System.out.println("Delimited Reverse: " + delimitedReverse);
    }
}

Here is the result:

Original: The quick brown fox jumps over the lazy dog
Reversed: god yzal eht revo spmuj xof nworb kciuq ehT
Delimited Reverse: dog lazy the over jumps fox brown quick The

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

How do I check if a string is empty or not?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class EmptyStringCheckDemo {
    public static void main(String[] args) {
        // Create some variable to hold some string that empty, contains only
        // white spaces and words.
        String one = "";
        String two = "\t\r\n";
        String three = "     ";
        String four = null;
        String five = "four four two";

        // We can use StringUtils class for checking if a string is empty or not
        // using StringUtils.isBlank() method. This method will return true if
        // the tested string is empty, contains white space only or null.
        System.out.println("Is one empty? " + StringUtils.isBlank(one));
        System.out.println("Is two empty? " + StringUtils.isBlank(two));
        System.out.println("Is three empty? " + StringUtils.isBlank(three));
        System.out.println("Is four empty? " + StringUtils.isBlank(four));
        System.out.println("Is five empty? " + StringUtils.isBlank(five));

        // On the other side, the StringUtils.isNotBlank() methods complement
        // the previous method. It will check is a tested string is not empty.
        System.out.println("Is one not empty? " + StringUtils.isNotBlank(one));
        System.out.println("Is two not empty? " + StringUtils.isNotBlank(two));
        System.out.println("Is three not empty? " + StringUtils.isNotBlank(three));
        System.out.println("Is four not empty? " + StringUtils.isNotBlank(four));
        System.out.println("Is five not empty? " + StringUtils.isNotBlank(five));
    }
}

Here is the result:

Is one empty? true
Is two empty? true
Is three empty? true
Is four empty? true
Is five empty? false

Is one not empty? false
Is two not empty? false
Is three not empty? false
Is four not empty? false
Is five not empty? true

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>