Example of Comparator in Java

UPDATED: 10 August 2016
Comparator<T>
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

You can use Comparable when you want natural ordering on class. 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 (Item.java)
import java.util.Comparator;

public class Item {

    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;
    }
    
    /**
     * Comparator to sort {@link Item} in ascending order by name.
     */
    public Comparator<Item> orderByNameASC(){
        return new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                if(o1 != null && o1.getName() != null
                        && o2 != null && o2.getName() != null){
                    return o1.getName().compareTo(o2.getName());
                }
                return -1;
            }
        };
    }
    
    /**
     * Comparator to sort {@link Item} in descending order by name.
     */
    public Comparator<Item> orderByNameDESC(){
        return new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                if(o1 != null && o1.getName() != null
                        && o2 != null && o2.getName() != null){
                    return o2.getName().compareTo(o1.getName());
                }
                return -1;
            }
        };
    }

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

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

/**
 * Example of Comparator.
 * @author javaQuery
 * @date 9th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class ComparatorExample {

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

        Item iPhone = new Item();
        iPhone.setName("iphone");

        List<Item> items = new ArrayList<Item>(2);
        items.add(samsung);
        items.add(iPhone);

        List<Item> clonedItems = new ArrayList<Item>(items);
        new ComparatorExample().usingPredefinedComparator(clonedItems);
        new ComparatorExample().usingInLineExpression(clonedItems);
        new ComparatorExample().usingLambdaExpression(new ArrayList<Item>(items));
    }

    /**
     * Print list to console
     *
     * @param items
     */
    private void printListData(List<Item> items) {
        for (Item item : items) {
            System.out.println(item);
        }
    }

    /**
     * Considering you've already created Comparators in your model.
     *
     * @param items
     */
    private void usingPredefinedComparator(List<Item> items) {
        System.out.println("Using Predefined Comparator (NAME#ASC)");
        System.out.println("===============================================");
        System.out.println("Before sort:");
        printListData(items);
        System.out.println("After sort(orderByNameASC):");
        Collections.sort(items, new Item().orderByNameASC());
        printListData(items);
    }
    
    /**
     * This is same as PredefinedComparator. 
     * Its only to show you how to use {@link Comparator} in-line.
     * @param items 
     */
    private void usingInLineExpression(List<Item> items){
        System.out.println("===============================================");
        System.out.println("Using Inline Expression (NAME#DESC)");
        System.out.println("===============================================");
        System.out.println("Before sort:");
        printListData(items);
        System.out.println("After sort(orderByNameDESC):");
        Collections.sort(items, new Comparator<Item>(){

            @Override
            public int compare(Item o1, Item o2) {
                if(o1 != null && o1.getName() != null
                        && o2 != null && o2.getName() != null){
                    return o2.getName().compareTo(o1.getName());
                }
                return -1;
            }
             
        });
        printListData(items);
    }
    
    /**
     * Using Lambda Expression in Java 1.8 or above.
     * @param items 
     */
    private void usingLambdaExpression(List<Item> items){
        System.out.println("===============================================");
        System.out.println("Using Lambda Expression (NAME#DESC)");
        System.out.println("===============================================");
        System.out.println("Before sort:");
        printListData(items);
        System.out.println("After sort(orderByNameASC):");
        Collections.sort(items, (Item o1, Item o2) -> {
            if(o1 != null && o1.getName() != null
                    && o2 != null && o2.getName() != null){
                return o1.getName().compareTo(o2.getName());
            }
            return -1;
        });
        printListData(items);
    }
}

Output
Using Predefined Comparator (NAME#ASC)
===============================================
Before sort:
Item{name=samsung, price=null}
Item{name=iphone, price=null}
After sort(orderByNameASC):
Item{name=iphone, price=null}
Item{name=samsung, price=null}
===============================================
Using Inline Expression (NAME#DESC)
===============================================
Before sort:
Item{name=iphone, price=null}
Item{name=samsung, price=null}
After sort(orderByNameDESC):
Item{name=samsung, price=null}
Item{name=iphone, price=null}
===============================================
Using Lambda Expression (NAME#ASC)
===============================================
Before sort:
Item{name=samsung, price=null}
Item{name=iphone, price=null}
After sort(orderByNameASC):
Item{name=iphone, price=null}
Item{name=samsung, price=null}

0 comments :