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:de.tudarmstadt.ukp.csniper.webapp.statistics.SortableAggregatedEvaluationResultDataProvider.java

private void updateView() {
    final SortParam<String> sp = getSort();

    // filter/*from   w  w  w .  ja va  2  s.c om*/
    if (!sp.getProperty().equals(lastSortProperty) || (lastSortOrder != sp.isAscending()) || filterChanged) {
        limitedResults = new ArrayList<AggregatedEvaluationResult>();
        for (AggregatedEvaluationResult aer : aerList) {
            if (getFilters().contains(aer.getClassification())) {
                limitedResults.add(aer);
            }
        }
    }

    // sort
    Collections.sort(limitedResults, new Comparator<AggregatedEvaluationResult>() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public int compare(AggregatedEvaluationResult aO1, AggregatedEvaluationResult aO2) {
            try {
                Comparable v1 = (Comparable) PropertyUtils.getNestedProperty(aO1, sp.getProperty());
                Comparable v2 = (Comparable) PropertyUtils.getNestedProperty(aO2, sp.getProperty());

                return sp.isAscending() ? v1.compareTo(v2) : v2.compareTo(v1);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    });

    lastSortProperty = sp.getProperty();
    lastSortOrder = sp.isAscending();
    filterChanged = false;
}

From source file:com.quinsoft.zeidon.domains.AbstractDomain.java

@Override
public int compare(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef,
        Object internalValue, Object externalValue) {
    try {/*from w w  w.  ja  v  a 2s  .co m*/
        Object value = convertExternalValue(task, attributeInstance, attributeDef, null, externalValue);
        Integer rc = compareNull(task, attributeDef, internalValue, value);
        if (rc != null)
            return rc;

        if (internalValue instanceof Comparable) {
            assert internalValue.getClass() == value.getClass();

            @SuppressWarnings("unchecked")
            Comparable<Object> c = (Comparable<Object>) internalValue;
            return c.compareTo(value);
        }

        DomainContext context = getContext(task, null); // Get the default context.
        return context.compare(task, internalValue, value);
    } catch (Throwable t) {
        throw ZeidonException.wrapException(t).prependAttributeDef(attributeDef);
    }
}

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

/**Compares this object with the specified object for order.
 *Returns a negative integer, zero, or a positive integer as this object
 *is less than, equal to, or greater than the specified object.
 *//*from  ww w.ja  va 2 s . co m*/
protected int compare(Object baseBean) {
    int compareValue = 0;

    if (dataClass == null || !dataClass.equals(baseBean.getClass())) {

        dataClass = baseBean.getClass();

        try {
            field = dataClass.getDeclaredField(fieldName);
            if (!field.isAccessible()) {
                throw new NoSuchFieldException();
            }
        } catch (NoSuchFieldException noSuchFieldException) {
            try {
                String methodName = "";

                if (isBoolean) {
                    methodName = "is" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
                } else {
                    methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
                }
                method = dataClass.getMethod(methodName, null);
            } catch (NoSuchMethodException noSuchMethodException) {
                LOG.error(noSuchMethodException.getMessage(), noSuchMethodException);
            }
        }
    } //End if field==null && method==null

    try {
        if (field != null && field.isAccessible()) {

            if (!isBoolean) {
                Comparable comparable = (Comparable) field.get(baseBean);
                if (comparable == null && fixedData == null) {
                    compareValue = 0;
                } else if (comparable == null) {
                    throw new UnsupportedOperationException();
                } else {
                    compareValue = comparable.compareTo(fixedData);
                }

            } else {
                if (((Boolean) field.get(baseBean)).booleanValue() == booleanFixedData)
                    compareValue = 0;
                else
                    compareValue = 1;
            }
        } else {
            if (!isBoolean) {
                Comparable comparable = (Comparable) method.invoke(baseBean, null);
                if (comparable == null && fixedData == null) {
                    compareValue = 0;
                } else if (comparable == null) {
                    throw new UnsupportedOperationException();
                } else if (comparable != null && fixedData == null) {
                    compareValue = -1;
                } else {
                    compareValue = comparable.compareTo(fixedData);
                }
            } else {
                Boolean booleanObj = (Boolean) method.invoke(baseBean, null);
                if (booleanObj == null) {
                    compareValue = -1;
                } else {
                    if (booleanObj.booleanValue() == booleanFixedData)
                        compareValue = 0;
                    else
                        compareValue = 1;
                }
            }
        }
    } catch (IllegalAccessException illegalAccessException) {
        LOG.error(illegalAccessException.getMessage(), illegalAccessException);
    } catch (InvocationTargetException invocationTargetException) {
        LOG.error(invocationTargetException.getMessage(), invocationTargetException);
    }
    return compareValue;
}

From source file:com.aurel.track.fieldType.runtime.base.CustomSelectComparable.java

@Override
public int compareTo(Object o) {
    CustomSelectComparable compositeComparable = (CustomSelectComparable) o;
    Map<Integer, Comparable> paramComparableMap = compositeComparable.getComparableMap();
    if ((comparableMap == null) && (paramComparableMap == null)) {
        return 0;
    }//w w  w  .  ja  va 2  s.  c o  m
    if (comparableMap == null) {
        return -1;
    }
    if (paramComparableMap == null) {
        return 1;
    }
    Iterator<Integer> itrComparableMap = comparableMap.keySet().iterator();
    while (itrComparableMap.hasNext()) {
        Integer key = itrComparableMap.next();
        Comparable value0 = comparableMap.get(key);
        Comparable value1 = paramComparableMap.get(key);
        if ((value0 == null) && (value1 == null)) {
            return 0;
        }
        if (value0 == null) {
            return -1;
        }
        if (value1 == null) {
            return 1;
        }
        try {
            int compareResult = value0.compareTo(value1);
            if (compareResult != 0) {
                //return now only if the part if different
                return compareResult;
            }
        } catch (Exception e) {
            LOGGER.warn("Sorting the values " + value0 + " of class " + value0.getClass().getName() + " and "
                    + value1 + " of class " + value1.getClass().getName() + " failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return 0;
}

From source file:dbs_project.index.performance.IndexTest.java

public void rangeQueriesTest() throws Exception {
    long time = 0;

    // sort/*from   ww w  .  j a v  a  2s.c  o  m*/
    List<Index> indexes = new ArrayList<>(table.getIndexes());
    Collections.sort(indexes, CMP);

    for (Index index : indexes) {
        SimpleColumn col = null;
        switch (index.getIndexMetaInfo().getKeyColumn().getMetaData().getType()) {
        case INTEGER:
            col = TPCHData.createForeignKeyColumn(0, "l_partkey", NUMBER_OF_QUERIES,
                    scaleFactor * TPCHData.PART_BASE_SIZE);
            break;
        case DOUBLE:
            col = TPCHData.createDoubleColumn(0, "l_extendedprice", NUMBER_OF_QUERIES, 1, 100000);
            break;
        case DATE:
            col = TPCHData.createDateColumn(0, "l_shipdate", NUMBER_OF_QUERIES, 694224000, 915148800);
            break;
        case STRING:
            col = TPCHData.createWordsColumn(0, "l_shipinstruct", NUMBER_OF_QUERIES, TPCHData.INSTRUCT, 1, 1);
            break;
        }
        long start = System.nanoTime();
        for (int i = 0; i < NUMBER_OF_QUERIES; i += 2) {
            IdCursor ids;
            Comparable date1 = (Comparable) col.getObject(i);
            Comparable date2 = (Comparable) col.getObject(i + 1);
            if (date1.compareTo(date2) < 0) {
                ids = index.rangeQueryRowIds(date1, date2, true, true);
            } else {
                ids = index.rangeQueryRowIds(date2, date1, true, true);
            }

            iterateIds(ids);
        }
        time += System.nanoTime() - start;

        //System.out.println(index.getIndexMetaInfo().getKeyColumn().getMetaData().getName() + ": " + (System.nanoTime() - start));
    }
    outputTime("rangeQueriesTest", scaleFactor, indexType, time);
}

From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java

/**
 * Sort events according to natural ordering of the values or a property.
 * @param events to sort/*from   w  w  w. jav a2 s  .c  o  m*/
 * @param property name of property providing sort values
 * @return sorted array
 */
public static EventBean[] sort(EventBean[] events, final String property) {
    List<EventBean> list = Arrays.asList(events);
    Collections.sort(list, new Comparator<EventBean>() {
        public int compare(EventBean o1, EventBean o2) {
            Comparable val1 = (Comparable) o1.get(property);
            Comparable val2 = (Comparable) o2.get(property);
            return val1.compareTo(val2);
        }
    });
    return list.toArray(new EventBean[list.size()]);
}

From source file:org.infoglue.cms.util.sorters.CompoundComparable.java

/**
 * Compares the n:th comparable of two <code>SortComparable</code> objects.
 * // w w w .j ava 2 s. c om
 * @param other the other <code>CompoundComparable</code> object.
 * @param index indicates which contained comparable to compare.
 * @return a negative integer, zero, or a positive integer if the n:th comparable of this object 
 *         is less than, equal to, or greater than the n:th comparable of the specified object.
 */
private final int compareTo(final CompoundComparable other, final int index) {
    final Comparable c1 = (Comparable) comparables.get(index);
    final Comparable c2 = (Comparable) other.comparables.get(index);
    final Boolean ascending = (Boolean) orders.get(index);
    return ascending.booleanValue() ? c1.compareTo(c2) : c2.compareTo(c1);
}

From source file:com.googlecode.jsfFlex.component.ext.AbstractFlexUIDataGridColumn.java

public synchronized Comparator<WrappedBeanEntry> getWrappedEntryAscendingComparator() {
    if (wrappedEntryAscendingComparator == null) {
        wrappedEntryAscendingComparator = new Comparator<WrappedBeanEntry>() {

            public int compare(WrappedBeanEntry entry1, WrappedBeanEntry entry2) {

                Object obj1 = entry1.getBeanEntry();
                Object obj2 = entry2.getBeanEntry();

                try {
                    Comparable<? super Object> act1 = (Comparable<? super Object>) ReflectionHelperUtil
                            .getValue(obj1, getDataFieldMethodName());
                    Comparable<? super Object> act2 = (Comparable<? super Object>) ReflectionHelperUtil
                            .getValue(obj2, getDataFieldMethodName());

                    return (act1.compareTo(act2) * -1);
                } catch (NoSuchMethodException noSuchMethodException) {
                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.append("NoSuchMethodException was thrown while invoking method : ");
                    errorMessage.append(getDataFieldMethodName());
                    throw new RuntimeException(errorMessage.toString(), noSuchMethodException);
                } catch (Exception additionalAccessException) {
                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.append(
                            "Other exception aside from NoSuchMethodException was thrown while invoking method : ");
                    errorMessage.append(getDataFieldMethodName());
                    throw new RuntimeException(errorMessage.toString(), additionalAccessException);
                }/* w w  w . ja  va2  s . com*/
            }

        };

    }

    return wrappedEntryAscendingComparator;
}

From source file:com.googlecode.jsfFlex.component.ext.AbstractFlexUIDataGridColumn.java

public synchronized Comparator<WrappedBeanEntry> getWrappedEntryDescendingComparator() {
    if (wrappedEntryDescendingComparator == null) {
        wrappedEntryDescendingComparator = new Comparator<WrappedBeanEntry>() {

            public int compare(WrappedBeanEntry entry1, WrappedBeanEntry entry2) {

                Object obj1 = entry1.getBeanEntry();
                Object obj2 = entry2.getBeanEntry();

                try {
                    Comparable<? super Object> act1 = (Comparable<? super Object>) ReflectionHelperUtil
                            .getValue(obj1, getDataFieldMethodName());
                    Comparable<? super Object> act2 = (Comparable<? super Object>) ReflectionHelperUtil
                            .getValue(obj2, getDataFieldMethodName());

                    return act1.compareTo(act2);
                } catch (NoSuchMethodException noSuchMethodException) {
                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.append("NoSuchMethodException was thrown while invoking method : ");
                    errorMessage.append(getDataFieldMethodName());
                    throw new RuntimeException(errorMessage.toString(), noSuchMethodException);
                } catch (Exception additionalAccessException) {
                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.append(
                            "Other exception aside from NoSuchMethodException was thrown while invoking method : ");
                    errorMessage.append(getDataFieldMethodName());
                    throw new RuntimeException(errorMessage.toString(), additionalAccessException);
                }/*from w w  w  .j  a  va  2 s .c o  m*/

            }

        };

    }

    return wrappedEntryDescendingComparator;
}

From source file:com.aurel.track.fieldType.runtime.base.CompositeComparable.java

@Override
public int compareTo(Object o) {
    CompositeComparable compositeComparable = (CompositeComparable) o;
    Map<Integer, Comparable> paramComparableMap = compositeComparable.getComparableMap();
    if ((comparableMap == null) && (paramComparableMap == null)) {
        return 0;
    }/*w w  w. j  av a  2s.c o  m*/
    if (comparableMap == null) {
        return -1;
    }
    if (paramComparableMap == null) {
        return 1;
    }
    for (int i = 0; i < numberOfParts; i++) {
        Integer parameterCode = new Integer(i + 1);
        Comparable value0 = comparableMap.get(parameterCode);
        Comparable value1 = paramComparableMap.get(parameterCode);
        if ((value0 == null) && (value1 == null)) {
            return 0;
        }
        if (value0 == null) {
            return -1;
        }
        if (value1 == null) {
            return 1;
        }
        try {
            int compareResult = value0.compareTo(value1);
            if (compareResult != 0) {
                //return now only if the part if different
                return compareResult;
            }
        } catch (Exception e) {
            LOGGER.warn("Sorting the values " + value0 + " of class " + value0.getClass().getName() + " and "
                    + value1 + " of class " + value1.getClass().getName() + " failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return 0;
}