Calculate Timings using Commons Lang StopWatch

You need to calculate timings of your code execution so you know how long a particular method or some block in your code take to finish it execution. Basically you can do this by capturing the start time and the end time using System.currentTimeMillis() and find the different. Another way to do it 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.example.commons.lang;

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

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

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        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 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: 0:00:03.000
Split 2: 0:00:05.525
Split 3: 0:00:06.525
Time: 6525

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.

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 class and append the properties that we will use the 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 override the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re gonna 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)) {
        return false;
    }
    DummyUser that = (DummyUser) obj;
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.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)) {
            return false;
        }
        DummyUser that = (DummyUser) obj;
        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

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

import java.util.Date;
import org.apache.commons.lang.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: Tue Apr 08 07:02:39 ICT 2008

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

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

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

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

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

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

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

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

Here are the program results:

now = 2008-04-05T00:34:55+07:00
nearestSecond = 2008-04-05T00:34:56+07:00
nearestMinute = 2008-04-05T00:35:00+07:00
nearestHour = 2008-04-05T01:00:00+07:00

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 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 DateFormatting {
    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 = 2007-03-04T15:05:11
timestamp = 2007-03-04T15:05:11+08:00
timestamp = Fri, 04 Mar 2007 15:05:11 +0800

How do I reverse a string, words or sentences?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class StringReverseExample {    
    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

How do I implement equals method using Commons Lang?

package org.kodejava.example.commons.lang;

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

import java.io.Serializable;

public class BookEqualsExample implements Serializable {
    private Long id;
    private String title;
    private String author;

    //~ Implements getters and setters here.

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof BookEqualsExample)) {
            return false;
        }

        BookEqualsExample that = (BookEqualsExample) o;
        return new EqualsBuilder()
                .append(this.id, that.id)
                .append(this.title, that.title)
                .append(this.author, that.author)
                .isEquals();

        // You can also use reflection of the EqualsBuilder class.
        // return EqualsBuilder.reflectionEquals(this, that);
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(id)
                .append(title)
                .append(author)
                .toHashCode();

        // Or even use the simplest method using reflection
        // below.
        // return HashCodeBuilder.reflectionHashCode(this);
    }
}

How do I implement hashCode using Commons Lang?

package org.kodejava.example.commons.lang;

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

import java.io.Serializable;

public class BookEqualsExample implements Serializable {
    private Long id;
    private String title;
    private String author;

    //~ Implements getters and setters here.

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof BookEqualsExample)) {
            return false;
        }

        BookEqualsExample that = (BookEqualsExample) o;
        return new EqualsBuilder()
                .append(this.id, that.id)
                .append(this.title, that.title)
                .append(this.author, that.author)
                .isEquals();

        // You can also use reflection of the EqualsBuilder class.
        // return EqualsBuilder.reflectionEquals(this, that);
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(id)
                .append(title)
                .append(author)
                .toHashCode();

        // Or even use the simplest method using reflection
        // below.
        // return HashCodeBuilder.reflectionHashCode(this);
    }
}

How do I use Apache Commons ToStringBuilder?

The toString() method defined in the java.lang.Object can be overridden when we want to give a more meaningful information about our object. We can simply return any information of the object in the toString() method, for instance the value of object’s states or fields.

The Apache Commons Lang library offers a good utility for creating this toString() information. Here I give a simple example using the ToStringBuilder class.

package org.kodejava.example.commons.lang;

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

public class ToStringBuilderExample {
    private String id;
    private String firstName;
    private String lastName;

    public ToStringBuilderExample() {
    }

    public static void main(String[] args) {
        ToStringBuilderExample example = new ToStringBuilderExample();
        example.id = "1";
        example.firstName = "First Name";
        example.lastName = "Last Name";

        System.out.println(example);
    }

    public String toString() {
        return new ToStringBuilder(this,
                ToStringStyle.MULTI_LINE_STYLE)
                .append("id", id)
                .append("firstName", firstName)
                .append("lastName", lastName)
                .toString();
    }
}

The ToStringStyle class allows us to choose the styling for our toString() method when we print it out. Here are the available styles that we can use.

  • ToStringStyle.DEFAULT_STYLE
  • ToStringStyle.MULTI_LINE_STYLE
  • ToStringStyle.NO_FIELD_NAMES_STYLE
  • ToStringStyle.SHORT_PREFIX_STYLE
  • ToStringStyle.SIMPLE_STYLE

The result of the code above is:

[email protected][
  id=1
  firstName=First Name
  lastName=Last Name
]

If you want to make the code event more simple by using the ToStringBuilder.reflectionToString() method to generate the string for the toString() method to return. Using this method the ToStringBuilder will the hard job of finding information about our class and return the string information.

Maven Dependencies:

<dependencies>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>