Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.cantaa.util.comparator;
 
Convenience Comporator. Makes it easy to sort lists that contain beans must sorting must be done on a property of that bean.
     // Sort list with cars on car's name:
     List<Car> carList = createCarlist();
     Collections.sort(carList, CarComparator.getInstance());

     class CarComparator extends AbstractComparator<Car> {
        public Comparable<?> getComparableValue(Car car) {
            return car.getName();
        }
     }
 

Author(s):
Hans Lesmeister
public abstract class AbstractComparator<T> implements Comparator<T> {
    private final boolean descend;
    public AbstractComparator() {
        this(false);
    }
    public AbstractComparator(boolean isDescend) {
        super();
         = isDescend;
    }
    @Override
    public int compare(T o1, T o2) {
        int smaller = -1;
        int bigger = 1;
        if () {
            int temp = smaller;
            smaller = bigger;
            bigger = temp;
        }
        // Both are null => equal
        if ((o1 == null) && (o2 == null)) {
            return 0;
        }
        if (o1 == null) {
            return smaller;
        }
        if (o2 == null) {
            return bigger;
        }
        if ((o1 instanceof Comparable) && (o2 instanceof Comparable)) {
            int retVal = ((Comparableo1).compareTo(o2);
            if (retVal < 0) {
                return smaller;
            }
            else if (retVal > 0) {
                return bigger;
            }
            else {
                return 0;
            }
        }
        else {
            Comparable<?> c1 = getComparableValue(o1);
            Comparable<?> c2 = getComparableValue(o2);
            return ComparableComparator.getInstance().compare(c1c2);  // Recursion
        }
    }

    
Determine the value to sort on

Parameters:
object The object eg. from the list that is being sorted. This value is never null
Returns:
The value/poperty that must be sorted on. Can be null but must be comparable
    abstract public Comparable<?> getComparableValue(T object);
New to GrepCode? Check out our FAQ X