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:com.aurel.track.fieldType.runtime.custom.select.CustomSelectSimpleRT.java

/**
 * Get the sort order related to the value
 * By default the value is directly used as sortOrder
 * the select fields has extra sortOrder columns 
 * @param fieldID//from  w w  w . ja v a2s.c  o  m
 * @param parameterCode
 * @param value the value the sortorder is looked for
 * @param workItemID
 * @param localLookupContainer 
 * @return
 */
@Override
public Comparable getSortOrderValue(Integer fieldID, Integer parameterCode, Object value, Integer workItemID,
        LocalLookupContainer localLookupContainer) {
    Integer[] optionIDs = CustomSelectUtil.getSelectedOptions(value);
    if (optionIDs == null || optionIDs.length == 0) {
        LOGGER.debug("No option seleced by getting the sort order value");
        return null;
    } else {
        ISortedBean sortedBean = null;
        Comparable minSortOrderValue = null;
        //Comparable listID = null;
        //Map beansMap = dropDownContainer.getDataSourceMap(MergeUtil.mergeKey(getDropDownMapFieldKey(fieldID), parameterCode));
        Map<Integer, ILabelBean> beansMap = localLookupContainer.getCustomOptionsMap();
        if (beansMap != null) {
            try {
                //select the option with the smallest sortorder
                for (int i = 0; i < optionIDs.length; i++) {
                    sortedBean = (ISortedBean) beansMap.get(optionIDs[i]);
                    if (sortedBean != null) {
                        if (sortedBean.getSortOrderValue() != null) {
                            Comparable currentSortOrder = sortedBean.getSortOrderValue();
                            if (minSortOrderValue == null
                                    || currentSortOrder.compareTo(minSortOrderValue) < 0) {
                                minSortOrderValue = currentSortOrder;
                                //add the list also because the sortOrder is local for the list
                                //but we might have entries from more lists even for the same field (depending on contexts) 
                                //listID = ((TOptionBean)sortedBean).getList();
                            }
                        } else {
                            //no sortOrder set. If null sortorder is returned the workItem.getAttribute() is taken as sororder
                            //but in this case it would be an Object[] which is not comparable (throws exception).
                            //As best effort return the value itself as Integer
                            minSortOrderValue = sortedBean.getObjectID();
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("The field number " + fieldID + " and parametercode " + parameterCode
                        + " doesn't implement the ISortedBean interface " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
        //SortedMap<Integer, Comparable> comparableMap = new TreeMap<Integer, Comparable>();
        //comparableMap.put(CustomSelectComparable.COMPARABLE_LIST, listID);
        //comparableMap.put(CustomSelectComparable.COMPARABLE_SORTORDER, minSortOrderValue);
        return minSortOrderValue;//new CustomSelectComparable(comparableMap);
    }
}

From source file:org.kuali.rice.krad.uif.util.MultiColumnComparator.java

/**
 * Compare the DataField values for the two modelCollection element indexes.
 * //from  ww w.ja va2  s . c  om
 * @param columnSort the comparison metadata (which column number, which direction, what type of
 *        sort)
 * @param protoField the prototype DataField for the column being sorted
 * @param index1 the index of the first modelCollection element for comparison
 * @param index2 the index of the second modelCollection element for comparison
 * @return 0 if the two elements are considered equal, a positive integer if the element at
 *         index1 is considered greater, else a negative integer
 */
private int compareDataFieldValues(ColumnSort columnSort, DataField protoField, Integer index1,
        Integer index2) {
    final int sortResult;// for DataFields, try to get the property value and use it directly

    final Object modelElement1 = modelCollection.get(index1);
    final Object modelElement2 = modelCollection.get(index2);

    // get the rest of the property path after the collection
    final String propertyPath = protoField.getBindingInfo().getBindingName();
    final Class<?> columnDataClass = getColumnDataClass(propertyPath);

    // we can do smart comparisons for Comparables
    if (Comparable.class.isAssignableFrom(columnDataClass)) {
        Comparable datum1 = (Comparable) ObjectPropertyUtils.getPropertyValue(modelElement1, propertyPath);
        Comparable datum2 = (Comparable) ObjectPropertyUtils.getPropertyValue(modelElement2, propertyPath);

        if (isOneNull(datum1, datum2)) {
            sortResult = compareOneIsNull(datum1, datum2);
        } else if (String.class.equals(columnDataClass)) {
            sortResult = columnTypeCompare((String) datum1, (String) datum2, columnSort.getSortType());
        } else {
            sortResult = datum1.compareTo(datum2);
        }
    } else { // resort to basic column string value comparison if the column data class isn't Comparable
        sortResult = compareFieldStringValues(columnSort, protoField, index1, index2);
    }

    return sortResult;
}

From source file:org.apache.jcs.utils.struct.SortedPreferentialArray.java

/**
 * This determines the position in the array that is occupied by an object that is larger or
 * equal to the argument. If none exists, -1 is returned.
 * <p>//from w  w  w . ja v  a 2 s .com
 * @param obj Object
 * @return Object
 */
private int findNearestOccupiedLargerOrEqualPosition(Comparable obj) {
    if (curSize == 0) {
        // nothing in the array
        return -1;
    }

    // this gives us an insert position.
    int pos = findNearestLargerEqualOrLastPosition(obj);

    // see if the previous will do to handle the empty insert spot position
    if (pos == curSize) { // && curSize < maxSize ) {
                          // pos will be > 0 if it equals curSize, we check for this above.
        if (obj.compareTo(array[pos - 1]) <= 0) {
            pos = pos - 1;
        } else {
            pos = -1;
        }
    } else {
        // the find nearest, returns the last, since it is used by insertion.
        if (obj.compareTo(array[pos]) > 0) {
            return -1;
        }
    }

    return pos;
}

From source file:org.janusgraph.graphdb.serializer.SerializerTest.java

License:asdf

@Test
public void testSerializedOrder() {
    serialize.registerClass(1, TClass1.class, new TClass1Serializer());

    final Map<Class, Factory> sortTypes = new HashMap<>();
    for (Map.Entry<Class, Factory> entry : TYPES.entrySet()) {
        if (serialize.isOrderPreservingDatatype(entry.getKey()))
            sortTypes.put(entry.getKey(), entry.getValue());
    }/*from w w  w .  ja v  a  2  s. co m*/
    assertEquals(10, sortTypes.size());
    for (int t = 0; t < 3000000; t++) {
        DataOutput o1 = serialize.getDataOutput(64);
        DataOutput o2 = serialize.getDataOutput(64);
        Map.Entry<Class, Factory> type = Iterables.get(sortTypes.entrySet(), random.nextInt(sortTypes.size()));
        Comparable c1 = (Comparable) type.getValue().newInstance();
        Comparable c2 = (Comparable) type.getValue().newInstance();
        o1.writeObjectByteOrder(c1, type.getKey());
        o2.writeObjectByteOrder(c2, type.getKey());
        StaticBuffer s1 = o1.getStaticBuffer();
        StaticBuffer s2 = o2.getStaticBuffer();
        assertEquals(Math.signum(c1.compareTo(c2)), Math.signum(s1.compareTo(s2)), 0.0);
        Object c1o = serialize.readObjectByteOrder(s1.asReadBuffer(), type.getKey());
        Object c2o = serialize.readObjectByteOrder(s2.asReadBuffer(), type.getKey());
        assertEquals(c1, c1o);
        assertEquals(c2, c2o);
    }

}

From source file:name.nanek.gdwprototype.shared.model.support.CompareToBuilder.java

/**
 * <p>Appends to the <code>builder</code> the comparison of
 * two <code>Object</code>s.</p>
 *
 * <ol>//w  w  w. j  a v a  2s . c o  m
 * <li>Check if <code>lhs == rhs</code></li>
 * <li>Check if either <code>lhs</code> or <code>rhs</code> is <code>null</code>,
 *     a <code>null</code> object is less than a non-<code>null</code> object</li>
 * <li>Check the object contents</li>
 * </ol>
 *
 * <p>If <code>lhs</code> is an array, array comparison methods will be used.
 * Otherwise <code>comparator</code> will be used to compare the objects.
 * If <code>comparator</code> is <code>null</code>, <code>lhs</code> must
 * implement {@link Comparable} instead.</p>
 *
 * @param lhs  left-hand object
 * @param rhs  right-hand object
 * @param comparator  <code>Comparator</code> used to compare the objects,
 *  <code>null</code> means treat lhs as <code>Comparable</code>
 * @return this - used to chain append calls
 * @throws ClassCastException  if <code>rhs</code> is not assignment-compatible
 *  with <code>lhs</code>
 * @since 2.0
 */
public CompareToBuilder append(Object lhs, Object rhs, Comparator<?> comparator) {
    if (comparison != 0) {
        return this;
    }
    if (lhs == rhs) {
        return this;
    }
    if (lhs == null) {
        comparison = -1;
        return this;
    }
    if (rhs == null) {
        comparison = +1;
        return this;
    }
    if (lhs.getClass().isArray()) {
        // switch on type of array, to dispatch to the correct handler
        // handles multi dimensional arrays
        // throws a ClassCastException if rhs is not the correct array type
        if (lhs instanceof long[]) {
            append((long[]) lhs, (long[]) rhs);
        } else if (lhs instanceof int[]) {
            append((int[]) lhs, (int[]) rhs);
        } else if (lhs instanceof short[]) {
            append((short[]) lhs, (short[]) rhs);
        } else if (lhs instanceof char[]) {
            append((char[]) lhs, (char[]) rhs);
        } else if (lhs instanceof byte[]) {
            append((byte[]) lhs, (byte[]) rhs);
        } else if (lhs instanceof double[]) {
            append((double[]) lhs, (double[]) rhs);
        } else if (lhs instanceof float[]) {
            append((float[]) lhs, (float[]) rhs);
        } else if (lhs instanceof boolean[]) {
            append((boolean[]) lhs, (boolean[]) rhs);
        } else {
            // not an array of primitives
            // throws a ClassCastException if rhs is not an array
            append((Object[]) lhs, (Object[]) rhs, comparator);
        }
    } else {
        // the simple case, not an array, just test the element
        if (comparator == null) {
            @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
            final Comparable<Object> comparable = (Comparable<Object>) lhs;
            comparison = comparable.compareTo(rhs);
        } else {
            @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
            final Comparator<Object> comparator2 = (Comparator<Object>) comparator;
            comparison = comparator2.compare(lhs, rhs);
        }
    }
    return this;
}

From source file:org.lockss.test.LockssTestCase.java

static public void assertCompareIsEqualTo(String msg, Comparable c1, Comparable c2) {
    int comp = c1.compareTo(c2);
    int revComp = c2.compareTo(c1);
    if (comp == 0 && revComp == 0) {
        return;/*from ww w.j a va  2 s. c o  m*/
    }

    if (comp == 0 || revComp == 0) {
        if (msg == null) {
            msg = "Inconsistent results.\n" + "Forward comparison is " + comp + "\n"
                    + "Reverse comparison returns " + revComp + "\n";
        } else {
            msg += " (inconsistent)";
        }
    } else {
        if (msg == null) {
            msg = "First compparable (" + c1 + ")" + " is not equal to than second (" + c2 + ")";
        }
    }
    fail(msg);
}

From source file:org.lockss.test.LockssTestCase.java

/**
 * Asserts that c1.compareTo(c2) > 0 and c2.compareTo(c1) < 0
 *///from w  w  w. ja  va2  s. c  o  m
static public void assertCompareIsGreaterThan(String msg, Comparable c1, Comparable c2) {
    int comp = c1.compareTo(c2);
    int revComp = c2.compareTo(c1);

    if (comp > 0 && revComp < 0) {
        return; //as asserted
    }

    if (comp == 0 && revComp == 0) {
        if (msg == null) {
            msg = c1 + " is equal to " + c2;
        } else {
            msg += " (equal)";
        }
    } else if (comp * revComp >= 0) {
        //one should be positive and the other neg
        if (msg != null) {
            msg = "Inconsistent comparison\n" + "Forward comparison returns " + comp + "\n"
                    + "While reverse comparison returns " + revComp + "\n";
        } else {
            msg += " (inconsistent)";
        }
    } else { //opposite of what we expected
        if (msg != null) {
            msg = "First comparable (" + c1 + ") is less than second (" + c2 + ")";
        }
    }
    fail(msg);
}

From source file:com.sri.ai.expresso.core.DefaultSyntaxLeaf.java

@Override
/**//w  w  w .j a  va  2  s. c  o m
 * Compares this Symbol to other syntax trees, placing it before {@link CompoundSyntaxTree}s and comparing
 * it to other Symbols by comparing their values if they are in the same type (as returned by {@link #getValueType()},
 * or their types if they are of different types.
 */
public int compareTo(Object another) {
    if (this == another) {
        return 0;
    }

    if (another instanceof CompoundSyntaxTree) {
        return -1; // Symbols come first
    }

    SyntaxLeaf anotherSymbol = null;
    if (another instanceof SyntaxLeaf) {
        anotherSymbol = (SyntaxLeaf) another;
    } else {
        anotherSymbol = createSyntaxLeaf(another);
        // Test again, as may have had self returned from the symbol table.
        if (this == anotherSymbol) {
            return 0;
        }
    }

    try {
        @SuppressWarnings("unchecked")
        Comparable<Object> value = (Comparable<Object>) getValue();
        @SuppressWarnings("unchecked")
        Comparable<Object> anotherValue = (Comparable<Object>) anotherSymbol.getValue();

        int result;
        String valueType = getValueType();
        String anotherValueType = anotherSymbol.getValueType();
        if (valueType.equals(anotherValueType)) {
            result = value.compareTo(anotherValue);
        } else {
            result = valueType.compareTo(anotherValueType);
        }
        return result;
    } catch (ClassCastException e) {
        throw new Error("Using DefaultSymbol.compareTo method with non-comparable values.", e);
    }
}

From source file:de.xirp.plugin.PluginManager.java

/**
 * Extracts files from the plugins jar./* w  ww  . j ava  2 s.  c  om*/
 * 
 * @param info
 *            the information about the plugin
 * @param destination
 *            destination for extraction
 * @param comparer
 *            comparer which returns <code>0</code> if an
 *            element from the jar should be extracted
 * @param replace
 *            string of the elements path which should be deleted
 * @param deleteOnExit
 *            <code>true</code> if the extracted files should be
 *            deleted on exit of the application.
 * @return <code>false</code> if an error occurred while
 *         extraction
 */
private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer,
        String replace, boolean deleteOnExit) {
    if (logClass.isTraceEnabled()) {
        logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$
                + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$
    }
    ZipInputStream zip = null;
    FileInputStream in = null;
    try {
        in = new FileInputStream(info.getAbsoluteJarPath());
        zip = new ZipInputStream(in);

        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            // relative name with slashes to separate dirnames.
            String elementName = entry.getName();
            // Check if it's an entry within Plugin Dir.
            // Only need to extract these

            if (comparer.compareTo(elementName) == 0) {
                // Remove Help Dir Name, because we don't like
                // to extract this parent dir
                elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ 

                if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$
                    // if parent dir for File does not exist,
                    // create
                    // it
                    File elementFile = new File(destination, elementName);
                    if (!elementFile.exists()) {
                        elementFile.getParentFile().mkdirs();
                        if (deleteOnExit) {
                            DeleteManager.deleteOnShutdown(elementFile);
                        }
                    }

                    // Only extract files, directorys are created
                    // above with mkdirs
                    if (!entry.isDirectory()) {
                        FileOutputStream fos = new FileOutputStream(elementFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = zip.read(buf)) > 0) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        elementFile.setLastModified(entry.getTime());
                    }
                    logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$
                }
            }
            zip.closeEntry();
        }

    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
    }

    return true;
}

From source file:BeanArrayList.java

/**
 * Filters a property using the Comparable.compareTo() on the porperty to
 * test for a range/*from  w  w w. j av  a2s  .  com*/
 * @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 BeanArrayList filtered on the range
 */
public BeanArrayList<T> getFiltered(String propertyName, boolean inclusive, Comparable fromValue,
        Comparable toValue) throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    HashMap cache = new HashMap();
    String currentClass = "";
    PropertyDescriptor pd = null;
    BeanArrayList<T> results = new BeanArrayList<T>();

    for (int i = 0; i < this.size(); i++) {
        T o = this.get(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;
}