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 are 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.


import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.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.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


Maven Central



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.