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) { = name;
        this.colour = colour;

    public String getName() {
        return name;

    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(colour, fruit.colour)

    public int hashCode() {
        return new HashCodeBuilder()

     * 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.colour, fruit.colour)
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

<!-- -->


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵


Leave a Reply