Calculate elapsed time using Apache Commons Lang StopWatch

You need to calculate timing or elapsed time of your code execution so you know how long a particular method or some block of code take to finish its execution. You can do this by capturing the start-time and the end-time using System.currentTimeMillis() and find their differences. Another way is to use the StopWatch class from Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang.time package.

The simplest steps to use the StopWatch is to create an instance of the StopWatch class, start the stopwatch by calling the start() method. After the stopwatch is started you can execute the target method or block of code you want to watch and call the stop() method to complete the timing session. To get the time of the stopwatch you can call the getTime() method.

Now, let’s see the code for the process described above.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingOne();
    }

    private void timingOne() {
        // Create an instance of StopWatch.
        StopWatch stopWatch = new StopWatch();

        // Start the watch, do some task and stop the watch.
        stopWatch.start();
        doSomeTask(5000);
        stopWatch.stop();

        // Print out the total time of the watch
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Here is the output of the code above:

Time: 5000

Beside doing a simple timing calculation using the start() and stop() followed by the getTime() methods, the StopWatch class also provides methods for splitting the time, suspend and resuming the stopwatch. You can use the split(), suspend() and resume() method respectively. To get the split time you can call the toSplitString() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchAnotherExample {
    public static void main(String[] args) {
        StopWatchAnotherExample demo = new StopWatchAnotherExample();
        demo.timingTwo();
    }

    private void timingTwo() {
        // Create an instance of StopWatch and start the stopwatch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Do some task and split the stopwatch time.
        doSomeTask(3000);
        stopWatch.split();
        System.out.println("Split 1: " + stopWatch.toSplitString());

        // Suspend the stopwatch and resume the stopwatch.
        stopWatch.suspend();
        doSomeTask(4000);
        stopWatch.resume();

        // Do some task and split the stopwatch time.
        doSomeTask(2500);
        stopWatch.split();
        System.out.println("Split 2: " + stopWatch.toSplitString());

        // Do some task and split the stopwatch time.
        doSomeTask(1000);
        stopWatch.split();
        System.out.println("Split 3: " + stopWatch.toSplitString());

        // Stop the stopwatch and the total execution time.
        stopWatch.stop();
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will output something like this:

Split 1: 00:00:03.004
Split 2: 00:00:05.518
Split 3: 00:00:06.522
Time: 6522

Another method that you can find in the StopWatch class is the getStartTime() which will return the stopwatch start time. The reset() method will reset the stopwatch. To remove a split you can call the unsplit() method.

Maven Dependencies

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

Maven Central

How do I clone an array variable?

You have an array variable, and you want to make a clone of this array into a new array variable. To do this you can use Apache Commons Lang ArrayUtils.clone() method. The code snippet below demonstrates the cloning of a primitive array that contains some integers elements in it.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class PrimitiveArrayClone {
    public static void main(String[] args) {
        int[] fibonacci = new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
        System.out.println("fibonacci = " + ArrayUtils.toString(fibonacci));

        int[] clone = ArrayUtils.clone(fibonacci);
        System.out.println("clone = " + ArrayUtils.toString(clone));
    }
}

The fibonacci array contents were cloned into the clone array, and we print out the content using ArrayUtils.toString() method.

fibonacci = {1,1,2,3,5,8,13,21,34,55}
clone = {1,1,2,3,5,8,13,21,34,55}

In the code snippet above the clone() method create a reference to a new array. The clone() method itself doesn’t change the original array. In addition to clone primitive arrays the clone() method also work for cloning array of objects.

As an example we will create an array of String objects and clone it using the ArrayUtils.clone() method. To display the contents of the array we will again use the ArrayUtils.toString() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ObjectArrayClone {
    public static void main(String[] args) {
        String[] colors = new String[]{"Red", "Green", "Blue", "Yellow"};
        System.out.println("colors = " + ArrayUtils.toString(colors));

        String[] clone = ArrayUtils.clone(colors);
        System.out.println("clone = " + ArrayUtils.toString(clone));
    }
}

And here is the result:

colors = {Red,Green,Blue,Yellow}
clone = {Red,Green,Blue,Yellow}

The only different between cloning a primitive array and object array using the ArrayUtils.clone() method is that when cloning an object such as String, Date, etc. we need to cast the result of the clone() method into the targeted object type.

Maven Dependencies

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

Maven Central

How do I print the contents of an array variable?

You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this you can use Apache Commons Lang ArrayUtils.toString() method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null, you can provide the second string argument to this method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // Print int array as string.
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // Print string array as string.
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // Print multidimensional array as string.
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // Return "Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

The output of the code snippet above:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

If you are using the JDK 1.5, or later you can actually use the java.util.Arrays class to do the same thing as the org.apache.commons.lang.ArrayUtils class does.

Maven Dependencies

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

Maven Central

How to implement the hashCode and equals method using Apache Commons?

This code snippet show you how to use HashCodeBuilder and EqualsBuilder class from the Apache Commons Lang library to implement the hashCode() and equals() method of an object. To use both of these classes we just need to create instance of these classes and append the properties that we will use to calculate the hashcode and to test for equality.

Implementing the hashCode() method first by creating the hashCode() method. Add the @Override annotation to make sure that we’ve overridden the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re going to use to calculate the hashcode. The final result of the actual hashcode can be obtained by calling the toHashCode() from the instance of HashCodeBuilder.

/**
 * Implement the hashCode method using HashCodeBuilder.
 */
@Override
public int hashCode() {
    return new HashCodeBuilder().append(id).append(name).toHashCode();
}

We do the same to create the equals() method. First create the method, it takes a single argument type of java.lang.Object. Add the @Override annotation to make sure we override the correct method. On the first line you can check to see if the passed object is an instance of the same object, we use the instanceof operator. We then compare the values stored in both object using the EqualsBuilder class. To get the equality result you must remember to call the isEquals() method.

/**
 * Implement the equals method using the EqualsBuilder.
 */
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof DummyUser that)) {
        return false;
    }
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.commons.lang;

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

public class DummyUser {
    private Long id;
    private String name;

    /**
     * Constructor to create an instance of this class.
     */
    public DummyUser() {
    }

    public static void main(String[] args) {
        DummyUser user1 = new DummyUser();
        user1.setId(10L);
        user1.setName("Carol");

        DummyUser user2 = new DummyUser();
        user2.setId(10L);
        user2.setName("Carol");

        System.out.println("user1.hashCode() = " + user1.hashCode());
        System.out.println("user2.hashCode() = " + user2.hashCode());

        System.out.println("user1.equals(user2) = " + user1.equals(user2));
    }

    // Getters & Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Implement the hashCode method using HashCodeBuilder.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(id).append(name).toHashCode();
    }

    /**
     * Implement the equals method using the EqualsBuilder.
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DummyUser that)) {
            return false;
        }
        return new EqualsBuilder().append(this.id, that.id)
                .append(this.name, that.name).isEquals();
    }
}

The result of our code are:

user1.hashCode() = 64902380
user2.hashCode() = 64902380
user1.equals(user2) = true

Maven Dependencies

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

Maven Central

How do I checks if two dates are on the same day?

In this example you’ll learn how to find out if two defined date objects are on the same day. It means that we are only interested in the date information and ignoring the time information of these date objects. We’ll be using an API provided by the Apache Commons Lang in this example. So here is the code snippet:

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class CheckSameDay {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date();

        // Checks to see if the dates is on the same day.
        if (DateUtils.isSameDay(date1, date2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", date1, date2);
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Checks to see if the calendars is on the same day.
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", cal1, cal2);
        }

        cal2.add(Calendar.DAY_OF_MONTH, 10);
        if (!DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is not on the same day.", cal1, cal2);
        }
    }
}

The example result produced by this snippet are:

31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 10/11/2021 is not on the same day.

Maven Dependencies

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

Maven Central

How do I generate a random alpha-numeric string?

The code below show you how to use the Apache Commons-Lang RandomStringUtils class to generate some random string data.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.RandomStringUtils;

public class RandomStringUtilsDemo {
    public static void main(String[] args) {
        // Creates a 64 chars length random string of number.
        String result = RandomStringUtils.random(64, false, true);
        System.out.println("random = " + result);

        // Creates a 64 chars length of random alphabetic string.
        result = RandomStringUtils.randomAlphabetic(64);
        System.out.println("random = " + result);

        // Creates a 32 chars length of random ascii string.
        result = RandomStringUtils.randomAscii(32);
        System.out.println("random = " + result);

        // Creates a 32 chars length of string from the defined array of
        // characters including numeric and alphabetic characters.
        result = RandomStringUtils.random(32, 0, 20, true, true,
                "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        System.out.println("random = " + result);
    }
}

The example of our program result are:

random = 6251115933802303614285104650603664973302700879175809706257640062
random = EbKuzxERdBtCCHtbRuYnLwfnirtIqkcwwHxvZofkaGLNsNblCaVoLXFxfjYjXSHk
random = v9cJK?=d-Jl b-pisn9vUGxCV1&*>StY
random = XirkhUHHfwUf3kih8Hw877882d9i8Q3q

Maven Dependencies

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

Maven Central

How do I find text between two strings?

In this example we’ll use the StringUtils.substringBetween() method. Here we’ll extract the title and body of our HTML document. Let’s see the code.

package org.kodejava.commons.lang;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

public class NestedString {
    public static void main(String[] args) {
        String helloHtml = "<html>" +
                "<head>" +
                "   <title>Hello World from Java</title>" +
                "<body>" +
                "Hello, today is: " + new Date() +
                "</body>" +
                "</html>";

        String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
        String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");

        System.out.println("title = " + title);
        System.out.println("content = " + content);
    }
}

By print out the title and content we’ll see something similar to:

title = Hello World from Java
content = Hello, today is: Thu Sep 30 06:32:32 CST 2021

Maven Dependencies

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

Maven Central

How do I check for an empty string?

StringUtils.isBlank() method check to see is the string contains only whitespace characters, empty or has a null value. If these conditions are true the strings are considered blank.

There’s also a StringUtils.isEmpty(), only this method doesn’t check for whitespaces-only string. For checking the opposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().

Using these methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy methods.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class CheckEmptyString {
    public static void main(String[] args) {
        String var1 = null;
        String var2 = "";
        String var3 = "    \t\t\t";
        String var4 = "Hello World";

        System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
        System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
        System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
        System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));

        System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
        System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
        System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
        System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));

        System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
        System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
        System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
        System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));

        System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
        System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
        System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
        System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
    }
}

The result of our program are:

var1 is blank? = true
var2 is blank? = true
var3 is blank? = true
var4 is blank? = false
var1 is not blank? = false
var2 is not blank? = false
var3 is not blank? = false
var4 is not blank? = true
var1 is empty? = true
var2 is empty? = true
var3 is empty? = false
var4 is empty? = false
var1 is not empty? = false
var2 is not empty? = false
var3 is not empty? = true
var4 is not empty? = true

Maven Dependencies

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

Maven Central

How do I get the nearest hour, minute, second of a date?

This example demonstrate how to use the DateUtils.round() method to get the nearest hour, minute and second of a date.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import java.util.Calendar;
import java.util.Date;

public class DateRoundingDemo {
    public static void main(String[] args) {
        FastDateFormat formatter = DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT;

        Date now = new Date();
        System.out.println("now = " + formatter.format(now));

        // Get the nearest second
        Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
        System.out.println("nearestSecond = " + formatter.format(nearestSecond));

        // Get the nearest minute
        Date nearestMinute = DateUtils.round(now, Calendar.MINUTE);
        System.out.println("nearestMinute = " + formatter.format(nearestMinute));

        // Get the nearest hour
        Date nearestHour = DateUtils.round(now, Calendar.HOUR);
        System.out.println("nearestHour = " + formatter.format(nearestHour));
    }
}

Here are the program results:

now = 2021-09-30T06:23:24+08:00
nearestSecond = 2021-09-30T06:23:24+08:00
nearestMinute = 2021-09-30T06:23:00+08:00
nearestHour = 2021-09-30T06:00:00+08:00

Maven Dependencies

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

Maven Central

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

import org.apache.commons.lang3.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_8601_EXTENDED_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_8601_EXTENDED_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 = 2021-09-30T06:18:20
timestamp = 2021-09-30T06:18:20+08:00
timestamp = Thu, 30 Sep 2021 06:18:20 +0800

Maven Dependencies

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

Maven Central