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>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

1 Comments

Leave a Reply