Example usage for java.lang Comparable compareTo

List of usage examples for java.lang Comparable compareTo

Introduction

In this page you can find the example usage for java.lang Comparable compareTo.

Prototype

public int compareTo(T o);

Source Link

Document

Compares this object with the specified object for order.

Usage

From source file:BeanVector.java

/**
 * Filters a property using the Comparable.compareTo() on the porperty to
 * test for a range/*from   www .j a v a  2s . co m*/
 * @param propertyName property to filter on
 * @param inclusive include the values of the range limiters
 * @param fromValue low range value
 * @param toValue high range value
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 * @return new BeanVector filtered on the range
 */
public BeanVector<T> getFiltered(String propertyName, boolean inclusive, Comparable fromValue,
        Comparable toValue) throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    Hashtable cache = new Hashtable();
    String currentClass = "";
    PropertyDescriptor pd = null;
    BeanVector<T> results = new BeanVector<T>();

    for (int i = 0; i < this.size(); i++) {
        T o = this.elementAt(i);

        if (!currentClass.equals(o.getClass().getName())) {
            pd = (PropertyDescriptor) cache.get(o.getClass().getName());

            if (pd == null) {
                PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
                boolean foundProperty = false;

                for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                    if (pds[pdi].getName().equals(propertyName)) {
                        pd = pds[pdi];
                        cache.put(o.getClass().getName(), pd);
                        foundProperty = true;
                    }
                }
            }
        }

        Comparable value = (Comparable) pd.getReadMethod().invoke(o);

        if ((value.compareTo(fromValue) > 0) && (value.compareTo(toValue) < 0)) {
            results.add(o);
        } else if (inclusive && ((value.compareTo(fromValue) == 0) || (value.compareTo(toValue) == 0))) {
            results.add(o);
        }
    }

    return results;
}

From source file:com.apptentive.android.sdk.module.engagement.logic.ComparisonPredicate.java

@Override
public boolean apply(Context context) {
    Log.v("Comparison Predicate: %s", query);
    Comparable value = getValue(context, query);
    Log.v("   => %s", value);
    for (Condition condition : conditions) {
        condition.operand = normalize(value, condition.operand);
        Log.v("-- Compare: %s %s %s", getLoggableValue(value), condition.operation,
                getLoggableValue(condition.operand));
        switch (condition.operation) {
        case $gt: {
            if (value == null) {
                return false;
            }//from   ww w . j a  v a 2 s .c  o  m
            if (condition.operand instanceof Comparable) {
                Comparable operand = (Comparable) condition.operand;
                if (!(value.compareTo(operand) > 0)) {
                    return false;
                }
            } else {
                throw new IllegalArgumentException(
                        String.format("Can't compare %s > %s", value, condition.operand));
            }
            break;
        }
        case $gte: {
            if (value == null) {
                return false;
            }
            if (condition.operand instanceof Comparable) {
                Comparable operand = (Comparable) condition.operand;
                if (!(value.compareTo(operand) >= 0)) {
                    return false;
                }
            } else {
                throw new IllegalArgumentException(
                        String.format("Can't compare %s >= %s", value, condition.operand));
            }
            break;
        }
        case $eq: {
            if (value == null) {
                return false;
            }
            if (condition.operand instanceof Comparable) {
                Comparable operand = (Comparable) condition.operand;
                if (!value.equals(operand)) {
                    return false;
                }
            } else {
                throw new IllegalArgumentException(
                        String.format("Can't compare %s == %s", value, condition.operand));
            }
            break;
        }
        case $ne: {
            if (value == null) {
                return false;
            }
            if (condition.operand instanceof Comparable) {
                Comparable operand = (Comparable) condition.operand;
                if (value.equals(operand)) {
                    return false;
                }
            } else {
                throw new IllegalArgumentException(
                        String.format("Can't compare %s != %s", value, condition.operand));
            }
            break;
        }
        case $lte: {
            if (value == null) {
                return false;
            }
            if (condition.operand instanceof Comparable) {
                Comparable operand = (Comparable) condition.operand;
                if (!(value.compareTo(operand) <= 0)) {
                    return false;
                }
            } else {
                throw new IllegalArgumentException(
                        String.format("Can't compare %s <= %s", value, condition.operand));
            }
            break;
        }
        case $lt: {
            if (value == null) {
                return false;
            }
            if (condition.operand instanceof Comparable) {
                Comparable operand = (Comparable) condition.operand;
                if (!(value.compareTo(operand) < 0)) {
                    return false;
                }
            } else {
                throw new IllegalArgumentException(
                        String.format("Can't compare %s < %s", value, condition.operand));
            }
            break;
        }
        case $exists: {
            if (!(condition.operand instanceof Boolean)) {
                throw new IllegalArgumentException(
                        String.format("Argument %s is not a boolean", condition.operand));
            }
            boolean shouldExist = (Boolean) condition.operand;
            boolean exists = value != null;
            return exists == shouldExist;
        }
        case $contains: {
            if (value == null) {
                return false;
            }
            boolean ret = false;
            if (value instanceof String && condition.operand instanceof String) {
                ret = ((String) value).toLowerCase().contains(((String) condition.operand).toLowerCase());
            }
            return ret;
        }
        case $starts_with: {
            if (value == null) {
                return false;
            }
            boolean ret = false;
            if (value instanceof String && condition.operand instanceof String) {
                ret = ((String) value).toLowerCase().startsWith(((String) condition.operand).toLowerCase());
            }
            return ret;
        }
        case $ends_with: {
            if (value == null) {
                return false;
            }
            boolean ret = false;
            if (value instanceof String && condition.operand instanceof String) {
                ret = ((String) value).toLowerCase().endsWith(((String) condition.operand).toLowerCase());
            }
            return ret;
        }
        default:
            break;
        }
    }
    return true;
}

From source file:org.kie.workbench.common.services.datamodeller.codegen.GenerationTools.java

public List<ObjectProperty> sortByName(List<ObjectProperty> properties) {
    Collections.sort(properties, new Comparator<ObjectProperty>() {
        public int compare(ObjectProperty o1, ObjectProperty o2) {

            if (o1 == null && o2 == null) {
                return 0;
            }//  w w  w .ja v  a 2s .c o m
            if (o1 == null && o2 != null) {
                return -1;
            }
            if (o1 != null && o2 == null) {
                return 1;
            }

            Comparable key1 = o1.getName();
            Comparable key2 = o2.getName();

            if (key1 == null && key2 == null) {
                return 0;
            }
            if (key1 != null && key2 != null) {
                return key1.compareTo(key2);
            }

            if (key1 == null && key2 != null) {
                return -1;
            }

            //if (key1 != null && key2 == null) return 1;
            return 1;
        }
    });
    return properties;
}

From source file:org.kie.workbench.common.services.datamodeller.codegen.GenerationTools.java

public List<Annotation> sortAnnotationsByName(List<Annotation> annotations) {
    Collections.sort(annotations, new Comparator<Annotation>() {
        public int compare(Annotation o1, Annotation o2) {

            if (o1 == null && o2 == null) {
                return 0;
            }/*w  w  w.j  a  v  a  2  s . c  om*/
            if (o1 == null && o2 != null) {
                return -1;
            }
            if (o1 != null && o2 == null) {
                return 1;
            }

            Comparable key1 = o1.getClassName();
            Comparable key2 = o2.getClassName();

            if (key1 == null && key2 == null) {
                return 0;
            }
            if (key1 != null && key2 != null) {
                return key1.compareTo(key2);
            }

            if (key1 == null && key2 != null) {
                return -1;
            }

            //if (key1 != null && key2 == null) return 1;
            return 1;
        }
    });
    return annotations;

}

From source file:com.google.gwt.dev.util.collect.HashMap.java

/**
 * Adapted from {@link org.apache.commons.collections.map.AbstractHashedMap}.
 *//*from ww w  .java2s  .c o m*/
protected void doWriteObject(ObjectOutputStream out) throws IOException {
    out.writeInt(keys.length);
    out.writeInt(size);

    if (stableWriteObject) {
        final Integer[] idx = new Integer[keys.length];
        for (int i = 0; i < keys.length; i++) {
            idx[i] = i;
        }
        Arrays.sort(idx, new Comparator<Integer>() {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            @Override
            public int compare(final Integer o1, final Integer o2) {
                Comparable c1 = (Comparable) (keys[o1]);
                Comparable c2 = (Comparable) (keys[o2]);
                if (c1 == null) {
                    // null < anything else
                    return (c2 == null) ? 0 : 1;
                }
                if (c2 == null) {
                    return -1;
                }
                return c1.compareTo(c2);
            }
        });

        for (int i = 0; i < keys.length; ++i) {
            int current = idx[i];
            Object key = keys[current];
            if (key != null) {
                out.writeObject(unmaskNullKey(key));
                out.writeObject(values[current]);
            }
        }
    } else {
        for (int i = 0; i < keys.length; ++i) {
            Object key = keys[i];
            if (key != null) {
                out.writeObject(unmaskNullKey(key));
                out.writeObject(values[i]);
            }
        }
    }
}

From source file:com.silverpeas.scheduler.simple.SchedulerJob.java

/**
 * Removes doubled entries (Comparable) , if the list is sorted
 *///from   ww w.ja v  a2s.c  om
private void removeDoubled(List<? extends Comparable> aList) {
    Comparable currentComparable;

    Comparable lastComparable = null;
    for (Iterator listIterator = aList.iterator(); listIterator.hasNext();) {
        try {
            if (lastComparable == null) {
                lastComparable = (Comparable) listIterator.next();
            } else {
                currentComparable = (Comparable) listIterator.next();
                if (lastComparable.compareTo(currentComparable) == 0) {
                    listIterator.remove();
                } else {
                    lastComparable = currentComparable;
                }
            }
        } catch (Exception aException) {
            // Unequal
        }
    }
}

From source file:org.kuali.coeus.common.budget.framework.query.QueryList.java

/**
 * sorts the QueryList by the fieldName in ascending or descending order.
 * Note: the field Object should be of Comparable type.
 * @return boolean indicating whether the sort is completed successfully or not.
 * @param ignoreCase use only when comparing strings. as default implementation uses case sensitive comparison.
 * @param fieldName field which is used to sort the bean.
 * @param ascending if true sorting is done in ascending order,
 * else sorting is done in descending order.
 *//*from w ww.  j a v  a  2s  . com*/
@SuppressWarnings("rawtypes")
public boolean sort(String fieldName, boolean ascending, boolean ignoreCase) {
    Object current, next;
    int compareValue = 0;
    Field field = null;
    Method method = null;
    if (this.size() == 0) {
        return false;
    }
    Class dataClass = get(0).getClass();
    String methodName = null;
    try {
        field = dataClass.getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        //field not available. Use method invokation.
        try {
            methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            method = dataClass.getMethod(methodName, null);
        } catch (NoSuchMethodException noSuchMethodException) {
            LOG.error(noSuchMethodException.getMessage(), noSuchMethodException);
            return false;
        }
    }

    for (int index = 0; index < size() - 1; index++) {
        for (int nextIndex = index + 1; nextIndex < size(); nextIndex++) {
            current = get(index);
            next = get(nextIndex);
            //Check if current and next implements Comparable else can't compare.
            //so return without comparing.May be we can have an exception for this purpose.
            try {
                if (field != null && field.isAccessible()) {
                    Comparable thisObj = (Comparable) field.get(current);
                    Comparable otherObj = (Comparable) field.get(next);
                    if (thisObj == null) {
                        compareValue = -1;
                    } else if (otherObj == null) {
                        compareValue = 1;
                    } else {
                        if (thisObj instanceof String && ignoreCase) {
                            compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj);
                        } else {
                            compareValue = thisObj.compareTo(otherObj);
                        }
                    }
                } else {
                    Comparable thisObj = null;
                    Comparable otherObj = null;
                    if (methodName != null) {
                        Method thisObjMethod = current.getClass().getMethod(methodName, null);
                        Method otherObjMethod = next.getClass().getMethod(methodName, null);
                        thisObj = (Comparable) thisObjMethod.invoke(current, null);
                        otherObj = (Comparable) otherObjMethod.invoke(next, null);
                    } else {
                        thisObj = (Comparable) method.invoke(current, null);
                        otherObj = (Comparable) method.invoke(next, null);
                    }
                    if (thisObj == null) {
                        compareValue = -1;
                    } else if (otherObj == null) {
                        compareValue = 1;
                    } else {
                        if (thisObj instanceof String && ignoreCase) {
                            compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj);
                        } else {
                            compareValue = thisObj.compareTo(otherObj);
                        }
                    }
                }
            } catch (IllegalAccessException illegalAccessException) {
                LOG.warn(illegalAccessException.getMessage());
                return false;
            } catch (InvocationTargetException invocationTargetException) {
                LOG.warn(invocationTargetException.getMessage(), invocationTargetException);
                return false;
            } catch (SecurityException e) {
                LOG.warn(e.getMessage(), e);
                return false;
            } catch (NoSuchMethodException e) {
                LOG.warn(e.getMessage(), e);
                return false;
            }

            if (ascending && compareValue > 0) {
                E temp = get(index);
                set(index, get(nextIndex));
                set(nextIndex, temp);
            } else if (!ascending && compareValue < 0) {
                E temp = get(index);
                set(index, get(nextIndex));
                set(nextIndex, temp);
            }

        }
    }
    return true;
}

From source file:BeanArrayList.java

/**
 * performs a selection sort on all the beans in the ArrayList by
 * PropertyName/*from  ww  w .  ja va2s.  c  om*/
 *
 * <p>You can use a mixture of bean classes as long as all the beans
 * support the same property (getName() for instance), and all have the
 * same return type, or can be compareTo()ed each other.</p>
 *
 * <p>For optimal performance, it is recommended that if you have a
 * mixed class set the you have them grouped with like classes together
 * as this will minimize reflection inspections.</p>
 * @param propertyName String value containing the property to sort on.
 * @param ascending == sorts up if true, down if not.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 */
public synchronized void sortOnProperty(String propertyName, boolean ascending)
        throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    T[] old = null;

    if ((this.indexPropertyName != null) && (this.changes != null)) {
        old = this.toTypedArray();
    }

    T temp = null;
    String currentClass = "";
    PropertyDescriptor pd = null;
    HashMap cache = new HashMap();

    for (int i = 0; i < (this.size() - 1); i++) {
        for (int j = i + 1; j < this.size(); j++) {
            T o1 = this.get(i);

            if (!currentClass.equals(o1.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o1.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            cache.put(o1.getClass().getName(), pd);
                            foundProperty = true;
                        }
                    }
                }
            }

            //System.out.println( "o1: "+o1+" "+pd);
            //System.out.println( propertyName +" "+ (pd == null ));
            Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1);

            T o2 = this.get(j);

            if (!currentClass.equals(o2.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o2.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            foundProperty = true;
                        }
                    }
                }
            }

            Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2);

            if (ascending) {
                if ((oc1 != oc2)
                        && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            } else {
                if ((oc1 != oc2)
                        && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            }
        }

        if (old != null) {
            changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray());
        }
    }
}

From source file:org.geoserver.catalog.impl.DefaultCatalogFacade.java

private Comparator<Object> comparator(final SortBy sortOrder) {
    return new Comparator<Object>() {
        @Override//from  ww w  . j av  a 2 s  . c om
        public int compare(Object o1, Object o2) {
            Object v1 = OwsUtils.get(o1, sortOrder.getPropertyName().getPropertyName());
            Object v2 = OwsUtils.get(o2, sortOrder.getPropertyName().getPropertyName());
            if (v1 == null) {
                if (v2 == null) {
                    return 0;
                } else {
                    return -1;
                }
            } else if (v2 == null) {
                return 1;
            }
            Comparable c1 = (Comparable) v1;
            Comparable c2 = (Comparable) v2;
            return c1.compareTo(c2);
        }
    };
}

From source file:BeanVector.java

/**
 * performs a selection sort on all the beans in the Vector by
 * PropertyName//from w  w  w .  ja v  a2 s. c  o m
 *
 * <p>You can use a mixture of bean classes as long as all the beans
 * support the same property (getName() for instance), and all have the
 * same return type, or can be compareTo()ed each other.</p>
 *
 * <p>For optimal performance, it is recommended that if you have a
 * mixed class set the you have them grouped with like classes together
 * as this will minimize reflection inspections.</p>
 * @param propertyName String value containing the property to sort on.
 * @param ascending == sorts up if true, down if not.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 */
public synchronized void sortOnProperty(String propertyName, boolean ascending)
        throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    T[] old = null;

    if ((this.indexPropertyName != null) && (this.changes != null)) {
        old = this.toTypedArray();
    }

    T temp = null;
    String currentClass = "";
    PropertyDescriptor pd = null;
    Hashtable cache = new Hashtable();

    for (int i = 0; i < (this.size() - 1); i++) {
        for (int j = i + 1; j < this.size(); j++) {
            T o1 = this.elementAt(i);

            if (!currentClass.equals(o1.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o1.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            cache.put(o1.getClass().getName(), pd);
                            foundProperty = true;
                        }
                    }
                }
            }

            //System.out.println( "o1: "+o1+" "+pd);
            //System.out.println( propertyName +" "+ (pd == null ));
            Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1);

            T o2 = this.elementAt(j);

            if (!currentClass.equals(o2.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o2.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            foundProperty = true;
                        }
                    }
                }
            }

            Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2);

            if (ascending) {
                if ((oc1 != oc2)
                        && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            } else {
                if ((oc1 != oc2)
                        && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            }
        }

        if (old != null) {
            changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray());
        }
    }
}