Example of Comparable in Java

UPDATED: 12 August 2016

Comparable<T>
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

You can use Comparator when you want different sorting option as per requirement. And you would also like to read How to sort List of Bean in Java? using Comparator and Comparable and How to sort Array in Ascending, Descending and Mixed mode in Java?

Source code (ComparableItem.java)
/**
 * Comparable item.
 * @author javaQuery
 * @date 11th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ComparableItem implements Comparable<ComparableItem>{

    private String name;
    private Double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
    
    @Override
    public int compareTo(ComparableItem item) {
        if(item != null && item.getName() != null){
            return this.getName().compareTo(item.getName());
        }
        return -1;
    }

    @Override
    public String toString() {
        return "ComparableItem{" + "name=" + name + ", price=" + price + '}';
    }
}

Source code (ComparableExample.java)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Example of Comparable.
 * @author javaQuery
 * @date 11th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ComparableExample {

    public static void main(String[] args) {
        ComparableItem samsung = new ComparableItem();
        samsung.setName("samsung");

        ComparableItem iphone = new ComparableItem();
        iphone.setName("iphone");

        List<ComparableItem> comparableItems = new ArrayList<ComparableItem>(2);
        comparableItems.add(samsung);
        comparableItems.add(iphone);
        
        new ComparableExample().performSort(comparableItems);
    }

    /**
     * Print list to console
     *
     * @param items
     */
    private void printListData(List<ComparableItem> items) {
        for (ComparableItem item : items) {
            System.out.println(item);
        }
    }
    
    /**
     * Perform sort on give List
     * @param comparableItems 
     */
    private void performSort(List<ComparableItem> comparableItems){
        System.out.println("Before sort:");
        printListData(comparableItems);
        System.out.println("===============================================");
        Collections.sort(comparableItems);
        System.out.println("After sort(orderByNameASC):");
        printListData(comparableItems);
    }
}

Output
Before sort:
ComparableItem{name=samsung, price=null}
ComparableItem{name=iphone, price=null}
===============================================
After sort(orderByNameASC):
ComparableItem{name=iphone, price=null}
ComparableItem{name=samsung, price=null}

0 comments :