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:org.molasdin.wbase.collections.list.ExtendedListDecorator.java

@SuppressWarnings("unchecked")
public void sort(final String property, Order order) {
    if (decorated().isEmpty()) {
        return;//from w  ww . java  2  s  . c om
    }

    T item = decorated().get(0);
    Comparator<T> tmp = null;
    if (ReflectionHelper.hasFunction(property, item)) {
        final Transformer<T, Object> transformer = new Transformer<T, Object>() {
            @Override
            public Object transform(T o) {
                return ReflectionHelper.functionValue(property, o);
            }
        };
        Object val = transformer.transform(item);
        final boolean isNatural = ReflectionHelper.supportsNaturalOrdering(val);
        tmp = new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                Object firstResult = transformer.transform(o1);
                Object secondResult = transformer.transform(o2);
                if (isNatural) {
                    Comparable f = (Comparable) firstResult;
                    Comparable s = (Comparable) secondResult;
                    return f.compareTo(s);
                }

                String f = ConvertUtils.convert(firstResult);
                String s = ConvertUtils.convert(secondResult);
                return f.compareTo(s);
            }
        };
    } else if (PropertyUtils.isReadable(item, property)) {
        tmp = new BeanComparator(property);
    } else {
        throw new RuntimeException("No property");
    }

    Collections.sort(decorated(), tmp);
}

From source file:org.hyperic.hq.ui.taglib.display.BeanSorter.java

/**
 * Compares two objects by first fetching a property from each object
 * and then comparing that value.  If there are any errors produced while
 * trying to compare these objects then a RunTimeException will be
 * thrown as any error found here will most likely be a programming
 * error that needs to be quickly addressed (like trying to compare
 * objects that are not comparable, or trying to read a property from a
 * bean that is invalid, etc...)/*from   w ww . j  a  v a  2s .co  m*/
 *
 * @throws RuntimeException if there are any problems making a comparison
 *    of the object properties.
 */

public int compare(Object o1, Object o2) throws RuntimeException {
    if (property == null) {
        throw new NullPointerException("Null property provided which " + "prevents BeanSorter sort");
    }

    try {
        Object p1 = null;
        Object p2 = null;

        // If they have supplied a decorator, then make sure and use it for
        // the sorting as well... TODO - Major hack....

        if (this.dec != null) {
            try {
                dec.initRow(o1, -1, -1);
                p1 = PropertyUtils.getProperty(dec, property);

                dec.initRow(o2, -1, -1);
                p2 = PropertyUtils.getProperty(dec, property);
            } catch (Exception e) {
                // If there were any problems, then assume that the decorator
                // does not implement that method, and instead fall down to
                // the original object...

                p1 = PropertyUtils.getProperty(o1, property);
                p2 = PropertyUtils.getProperty(o2, property);
            }
        } else {
            p1 = PropertyUtils.getProperty(o1, property);
            p2 = PropertyUtils.getProperty(o2, property);
        }

        if (p1 instanceof Comparable && p2 instanceof Comparable) {
            Comparable c1 = (Comparable) p1;
            Comparable c2 = (Comparable) p2;
            return c1.compareTo(c2);
        } else {
            throw new RuntimeException(
                    "Object returned by property \"" + property + "\" is not a Comparable object");
        }
    } catch (IllegalAccessException e) {
        throw new RuntimeException("IllegalAccessException thrown while " + "trying to fetch property \""
                + property + "\" during sort");
    } catch (InvocationTargetException e) {
        throw new RuntimeException("InvocationTargetException thrown while " + "trying to fetch property \""
                + property + "\" during sort");
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("NoSuchMethodException thrown while " + "trying to fetch property \""
                + property + "\" during sort");
    }
}

From source file:com.opensymphony.xwork2.validator.validators.RangeValidatorSupport.java

protected void validateValue(Object object, Comparable<T> value, T min, T max) {
    setCurrentValue(value);//from   ww  w  .  j  a v a2s. c  o m

    // only check for a minimum value if the min parameter is set
    if ((min != null) && (value.compareTo(min) < 0)) {
        addFieldError(getFieldName(), object);
    }

    // only check for a maximum value if the max parameter is set
    if ((max != null) && (value.compareTo(max) > 0)) {
        addFieldError(getFieldName(), object);
    }

    setCurrentValue(null);
}

From source file:org.nuclos.common.collect.collectable.CollectableComparatorFactory.java

/**
 * @return comparator that sorts by id field
 * @precondition clctEntityField != null
 *//*from  w  ww. j a  va 2s. c om*/
public Comparator<Clct> newCollectableIdComparator() {
    return new Comparator<Clct>() {

        @Override
        public int compare(Clct clct1, Clct clct2) {
            int result = 0;

            Object oId1 = clct1.getId();
            Object oId2 = clct2.getId();
            if (oId1 instanceof Comparable<?> && oId2 instanceof Comparable<?>) {
                Comparable<Object> comp1 = (Comparable<Object>) oId1;
                Comparable<Object> comp2 = (Comparable<Object>) oId2;
                result = comp1 == null ? 1 : comp2 == null ? -1 : comp1.compareTo(oId2);
            }
            return result;
        }
    };
}

From source file:org.kuali.kfs.sys.DynamicCollectionComparator.java

/**
 * compare the two given objects 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. If the objects implement Comparable interface, the objects compare with each
 * other based on the implementation; otherwise, the objects will be converted into Strings and compared as String.
 *//*from w w w  . j  av  a  2 s .  c  o  m*/
public int compare(T object0, T object1, String fieldName) {
    int comparisonResult = 0;

    try {
        Object propery0 = PropertyUtils.getProperty(object0, fieldName);
        Object propery1 = PropertyUtils.getProperty(object1, fieldName);

        if (propery0 == null && propery1 == null) {
            comparisonResult = 0;
        } else if (propery0 == null) {
            comparisonResult = -1;
        } else if (propery1 == null) {
            comparisonResult = 1;
        } else if (propery0 instanceof Comparable) {
            Comparable comparable0 = (Comparable) propery0;
            Comparable comparable1 = (Comparable) propery1;

            comparisonResult = comparable0.compareTo(comparable1);
        } else {
            String property0AsString = ObjectUtils.toString(propery0);
            String property1AsString = ObjectUtils.toString(propery1);

            comparisonResult = property0AsString.compareTo(property1AsString);
        }
    } catch (IllegalAccessException e) {
        throw new RuntimeException("unable to compare property: " + fieldName, e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("unable to compare property: " + fieldName, e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("unable to compare property: " + fieldName, e);
    }

    return comparisonResult * this.getSortOrderAsNumber();
}

From source file:org.structr.core.graph.search.PropertySearchAttribute.java

private int compare(T nodeValue, T searchValue) {

    if (nodeValue instanceof Comparable && searchValue instanceof Comparable) {

        Comparable n = (Comparable) nodeValue;
        Comparable s = (Comparable) searchValue;

        return n.compareTo(s);
    }/*from w w w. ja v a2s  .c o  m*/

    return 0;
}

From source file:org.pentaho.reporting.engine.classic.core.function.ItemMinFunction.java

/**
 * Receives notification that a row of data is being processed. Reads the data from the field defined for this
 * function and calculates the minimum value.
 *
 * @param event//  ww w.  java2 s .c  om
 *          Information about the event.
 */
public void itemsAdvanced(final ReportEvent event) {
    if (field == null) {
        return;
    }

    final Object fieldValue = event.getDataRow().get(getField());
    if (fieldValue instanceof Comparable == false) {
        return;
    }
    try {
        final Comparable compare = (Comparable) fieldValue;

        final Comparable oldValue = min.get(lastGroupSequenceNumber);
        if (oldValue == null || oldValue.compareTo(compare) > 0) {
            min.set(lastGroupSequenceNumber, compare);
        }
    } catch (Exception e) {
        ItemMinFunction.logger.error("ItemMinFunction.advanceItems(): problem adding number.");
    }
}

From source file:org.pentaho.reporting.engine.classic.core.function.ItemMaxFunction.java

/**
 * Receives notification that a row of data is being processed. Reads the data from the field defined for this
 * function and performs the maximum value comparison with its old value.
 *
 * @param event/*from  www .  j  a va  2 s.  c o m*/
 *          Information about the event.
 */
public void itemsAdvanced(final ReportEvent event) {
    if (field == null) {
        return;
    }

    final Object fieldValue = event.getDataRow().get(getField());
    if (fieldValue instanceof Comparable == false) {
        return;
    }

    try {
        final Comparable compare = (Comparable) fieldValue;

        final Comparable oldValue = max.get(lastGroupSequenceNumber);
        if (oldValue == null || oldValue.compareTo(compare) < 0) {
            max.set(lastGroupSequenceNumber, compare);
        }
    } catch (Exception e) {
        ItemMaxFunction.logger.error("ItemMaxFunction.advanceItems(): problem comparing number.");
    }
}

From source file:com.linkedin.pinot.core.query.pruner.ColumnValueSegmentPruner.java

/**
 * Helper method to determine if a segment can be pruned based on the column min/max value in segment metadata and
 * the predicates on time column. The algorithm is as follows:
 *
 * <ul>/*from w ww  .  j av  a 2s  .c  o m*/
 *   <li> For leaf node: Returns true if there is a predicate on the column and apply the predicate would result in
 *   filtering out all docs of the segment, false otherwise. </li>
 *   <li> For non-leaf AND node: True if any of its children returned true, false otherwise. </li>
 *   <li> For non-leaf OR node: True if all its children returned true, false otherwise. </li>
 * </ul>
 *
 * @param filterQueryTree Filter tree for the query.
 * @param columnMetadataMap Map from column name to column metadata.
 * @return True if segment can be pruned out, false otherwise.
 */
@SuppressWarnings("unchecked")
@Override
public boolean pruneSegment(@Nonnull FilterQueryTree filterQueryTree,
        @Nonnull Map<String, ColumnMetadata> columnMetadataMap) {
    FilterOperator filterOperator = filterQueryTree.getOperator();
    List<FilterQueryTree> children = filterQueryTree.getChildren();

    if (children == null || children.isEmpty()) {
        // Leaf Node

        // Skip operator other than EQUALITY and RANGE
        if ((filterOperator != FilterOperator.EQUALITY) && (filterOperator != FilterOperator.RANGE)) {
            return false;
        }

        ColumnMetadata columnMetadata = columnMetadataMap.get(filterQueryTree.getColumn());
        if (columnMetadata == null) {
            // Should not reach here after DataSchemaSegmentPruner
            return true;
        }

        Comparable minValue = columnMetadata.getMinValue();
        Comparable maxValue = columnMetadata.getMaxValue();

        if (filterOperator == FilterOperator.EQUALITY) {
            // EQUALITY

            // Doesn't have min/max value set in metadata
            if ((minValue == null) || (maxValue == null)) {
                return false;
            }

            // Check if the value is in the min/max range
            FieldSpec.DataType dataType = columnMetadata.getDataType();
            Comparable value = getValue(filterQueryTree.getValue().get(0), dataType);
            return (value.compareTo(minValue) < 0) || (value.compareTo(maxValue) > 0);
        } else {
            // RANGE

            // Get lower/upper boundary value
            FieldSpec.DataType dataType = columnMetadata.getDataType();
            RangePredicate rangePredicate = new RangePredicate(null, filterQueryTree.getValue());
            String lowerBoundary = rangePredicate.getLowerBoundary();
            boolean includeLowerBoundary = rangePredicate.includeLowerBoundary();
            Comparable lowerBoundaryValue = null;
            if (!lowerBoundary.equals(RangePredicate.UNBOUNDED)) {
                lowerBoundaryValue = getValue(lowerBoundary, dataType);
            }
            String upperBoundary = rangePredicate.getUpperBoundary();
            boolean includeUpperBoundary = rangePredicate.includeUpperBoundary();
            Comparable upperBoundaryValue = null;
            if (!upperBoundary.equals(RangePredicate.UNBOUNDED)) {
                upperBoundaryValue = getValue(upperBoundary, dataType);
            }

            // Check if the range is valid
            if ((lowerBoundaryValue != null) && (upperBoundaryValue != null)) {
                if (includeLowerBoundary && includeUpperBoundary) {
                    if (lowerBoundaryValue.compareTo(upperBoundaryValue) > 0) {
                        return true;
                    }
                } else {
                    if (lowerBoundaryValue.compareTo(upperBoundaryValue) >= 0) {
                        return true;
                    }
                }
            }

            // Doesn't have min/max value set in metadata
            if ((minValue == null) || (maxValue == null)) {
                return false;
            }

            if (lowerBoundaryValue != null) {
                if (includeLowerBoundary) {
                    if (lowerBoundaryValue.compareTo(maxValue) > 0) {
                        return true;
                    }
                } else {
                    if (lowerBoundaryValue.compareTo(maxValue) >= 0) {
                        return true;
                    }
                }
            }
            if (upperBoundaryValue != null) {
                if (includeUpperBoundary) {
                    if (upperBoundaryValue.compareTo(minValue) < 0) {
                        return true;
                    }
                } else {
                    if (upperBoundaryValue.compareTo(minValue) <= 0) {
                        return true;
                    }
                }
            }
            return false;
        }
    } else {
        // Parent node
        return pruneNonLeaf(filterQueryTree, columnMetadataMap);
    }
}

From source file:org.polymap.rhei.field.BetweenFormField.java

public void fireEvent(Object eventSrc, int eventCode, Object newValue) {
    log.debug("fireEvent(): ev=" + eventCode + ", newValue=" + newValue);

    if (eventCode == IFormFieldListener.VALUE_CHANGE && eventSrc == field1) {
        newValue1 = newValue;//from   w  ww.j a  va  2  s  .  co  m
        //            newValue2 = newValue2 == null ? newValue1 : newValue2;
    }
    if (eventCode == IFormFieldListener.VALUE_CHANGE && eventSrc == field2) {
        newValue2 = newValue;
        //            newValue1 = newValue1 == null ? newValue2 : newValue1;
    }
    if (newValue1 instanceof Comparable && newValue2 instanceof Comparable) {
        Comparable c1 = (Comparable) newValue1;
        Comparable c2 = (Comparable) newValue2;
        if (c1.compareTo(c2) > 0) {
            newValue2 = newValue1;
        }
    }

    Object value = newValue1 != null || newValue2 != null ? new Object[] { newValue1, newValue2 } : null;
    site.fireEvent(this, eventCode, value);
}