How do I reverse array elements order?

In this example we are going to use the ArraysUtils helper class from the 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 another type of array such as java.lang.Object, long, int, short, char, byte, double, float and boolean.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayReverseExample {

    public static void main(String[] args) {
        // Define the "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

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

Maven Central

How do I count word occurrences in a string?

package org.kodejava.commons.lang;

import org.apache.commons.lang3.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 example.";
        // The word we want to count its occurrences
        String word = "you";

        // Using StringUtils.countMatches() method we can count the occurrence
        // 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

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

Maven Central

How do I reverse a string, words or sentences?

package org.kodejava.commons.lang;

import org.apache.commons.lang3.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

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

Maven Central

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

package org.kodejava.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class EmptyStringCheckDemo {
    public static void main(String[] args) {
        // Create some variable to hold some empty string, contains only
        // whitespaces 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 whitespaces 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 if 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

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

Maven Central

How do I implement equals() method using EqualsBuilder class?

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 objects using the EqualsBuilder class. To get the equality result, we 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 is 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 results 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.13.0</version>
</dependency>

Maven Central