List of usage examples for java.lang Comparable compareTo
public int compareTo(T o);
From source file:org.jfree.data.KeyedObjectComparator.java
/** * Compares two {@link KeyedValue} instances and returns an * <code>int</code> that indicates the relative order of the two objects. * * @param o1 object 1.//w ww .j ava 2 s.c om * @param o2 object 2. * * @return An int indicating the relative order of the objects. */ public int compare(Object o1, Object o2) { if (o2 == null) { return -1; } if (o1 == null) { return 1; } KeyedObject ko1 = (KeyedObject) o1; KeyedObject ko2 = (KeyedObject) o2; if (this.type == KeyedObjectComparatorType.BY_KEY) { if (this.order.equals(SortOrder.ASCENDING)) { return ko1.getKey().compareTo(ko2.getKey()); } else if (this.order.equals(SortOrder.DESCENDING)) { return ko2.getKey().compareTo(ko1.getKey()); } else { throw new IllegalArgumentException("Unrecognised sort order."); } } else if (this.type == KeyedObjectComparatorType.BY_VALUE) { Object n1 = ko1.getObject(); Object n2 = ko2.getObject(); Comparable c1 = "FALLBACK"; if (n1 instanceof Comparable) { c1 = (Comparable) n1; } Comparable c2 = "FALLBACK"; if (n2 instanceof Comparable) { c2 = (Comparable) n2; } if (n2 == null) { return -1; } if (n1 == null) { return 1; } if (this.order.equals(SortOrder.ASCENDING)) { return c1.compareTo(c2); } else if (this.order.equals(SortOrder.DESCENDING)) { return c2.compareTo(c1); } else { throw new IllegalArgumentException("Unrecognised sort order."); } } else { throw new IllegalArgumentException("Unrecognised type."); } }
From source file:com.linkedin.pinot.core.realtime.converter.stats.RealtimeColumnStatistics.java
@Override public boolean isSorted() { // Multivalue columns can't be in sorted order if (!_block.getMetadata().isSingleValue()) { return false; }/* w w w. j a v a 2 s . c o m*/ // If this is a single value, then by definition the data is sorted final int blockLength = _block.getMetadata().getLength(); if (blockLength <= 1 || getCardinality() <= 1) { return true; } // Iterate over all data to figure out whether or not it's in sorted order SingleColumnSingleValueReader singleValueReader = ((RealtimeSingleValueBlock) _block).getReader(); int docIdIndex = _sortedDocIdIterationOrder != null ? _sortedDocIdIterationOrder[0] : 0; int dictionaryId = singleValueReader.getInt(docIdIndex); Comparable previousValue = (Comparable) _dictionaryReader.get(dictionaryId); for (int i = 1; i < blockLength; i++) { docIdIndex = _sortedDocIdIterationOrder != null ? _sortedDocIdIterationOrder[i] : i; dictionaryId = singleValueReader.getInt(docIdIndex); Comparable currentValue = (Comparable) _dictionaryReader.get(dictionaryId); // If previousValue is greater than currentValue if (0 < previousValue.compareTo(currentValue)) { return false; } else { previousValue = currentValue; } } return true; }
From source file:org.apache.hadoop.hive.metastore.hbase.PartitionKeyComparator.java
@Override public int compareTo(byte[] value, int offset, int length) { byte[] bytes = Arrays.copyOfRange(value, offset, offset + length); if (LOG.isDebugEnabled()) { LOG.debug("Get key " + new String(bytes)); }/*from ww w . j a v a2 s . c o m*/ BinarySortableSerDe serDe = new BinarySortableSerDe(); List deserializedkeys = null; try { serDe.initialize(new Configuration(), serdeProps); deserializedkeys = ((List) serDe.deserialize(new BytesWritable(bytes))).subList(2, 2 + names.split(",").length); } catch (SerDeException e) { // don't bother with failed deserialization, continue with next key return 1; } for (int i = 0; i < ranges.size(); i++) { Range range = ranges.get(i); NativeRange nativeRange = nativeRanges.get(i); Comparable partVal = (Comparable) deserializedkeys.get(nativeRange.pos); if (LOG.isDebugEnabled()) { LOG.debug("Try to match range " + partVal + ", start " + nativeRange.start + ", end " + nativeRange.end); } if (range.start == null || range.start.inclusive && partVal.compareTo(nativeRange.start) >= 0 || !range.start.inclusive && partVal.compareTo(nativeRange.start) > 0) { if (range.end == null || range.end.inclusive && partVal.compareTo(nativeRange.end) <= 0 || !range.end.inclusive && partVal.compareTo(nativeRange.end) < 0) { continue; } } if (LOG.isDebugEnabled()) { LOG.debug("Fail to match range " + range.keyName + "-" + partVal + "[" + nativeRange.start + "," + nativeRange.end + "]"); } return 1; } for (int i = 0; i < ops.size(); i++) { Operator op = ops.get(i); NativeOperator nativeOp = nativeOps.get(i); switch (op.type) { case LIKE: if (!deserializedkeys.get(nativeOp.pos).toString().matches(op.val)) { if (LOG.isDebugEnabled()) { LOG.debug("Fail to match operator " + op.keyName + "(" + deserializedkeys.get(nativeOp.pos) + ") LIKE " + nativeOp.val); } return 1; } break; case NOTEQUALS: if (nativeOp.val.equals(deserializedkeys.get(nativeOp.pos))) { if (LOG.isDebugEnabled()) { LOG.debug("Fail to match operator " + op.keyName + "(" + deserializedkeys.get(nativeOp.pos) + ")!=" + nativeOp.val); } return 1; } break; } } if (LOG.isDebugEnabled()) { LOG.debug("All conditions satisfied:" + deserializedkeys); } return 0; }
From source file:viper.api.time.MultipleRange.java
/** * {@inheritDoc}//from w w w .j a v a 2 s. c o m */ public Comparable endOf(Comparable c) { if (c == null) { return null; } if (subs.length == 0) { return null; } Comparable eo = subs[0].endOf(c); for (int i = 1; i < subs.length; i++) { Comparable temp = subs[i].endOf(c); if ((eo == null) || (temp != null && eo.compareTo(temp) < 0)) { eo = temp; } } return eo; }
From source file:com.jd.survey.domain.survey.SurveyPage.java
@Override public int compareTo(SurveyPage that) { final int BEFORE = -1; final int AFTER = 1; if (that == null) { return BEFORE; }/* w w w . ja v a2 s . c o m*/ Comparable<Short> thisSurveyPage = this.getOrder(); Comparable<Short> thatSurveyPage = that.getOrder(); if (thisSurveyPage == null) { return AFTER; } else if (thatSurveyPage == null) { return BEFORE; } else { return thisSurveyPage.compareTo(that.getOrder()); } }
From source file:net.jazdw.rql.parser.listfilter.ListFilter.java
@SuppressWarnings("unchecked") @Override/*from ww w . ja v a 2 s. c o m*/ public List<T> visit(ASTNode node, List<T> list) { switch (node.getName()) { case "and": for (Object obj : node) { if (obj instanceof ASTNode) { list = ((ASTNode) obj).accept(this, list); } else { throw new UnsupportedOperationException("Encountered a non-ASTNode argument in AND statement"); } } return list; case "or": Set<T> set = new LinkedHashSet<T>(); for (Object obj : node) { if (obj instanceof ASTNode) { set.addAll(((ASTNode) obj).accept(this, list)); } else { throw new UnsupportedOperationException("Encountered a non-ASTNode argument in OR statement"); } } return new ArrayList<>(set); case "eq": case "gt": case "ge": case "lt": case "le": case "ne": String propName = (String) node.getArgument(0); Object test = node.getArgumentsSize() > 1 ? node.getArgument(1) : null; List<T> result = new ArrayList<>(); for (T item : list) { Object property = getProperty(item, propName); Comparable<Object> comparableProperty; if (property instanceof Comparable) { comparableProperty = (Comparable<Object>) property; } else { throw new UnsupportedOperationException( String.format("Property '%s' is not comparable", propName)); } int comparisonValue; try { comparisonValue = comparableProperty.compareTo(test); } catch (ClassCastException e) { throw new UnsupportedOperationException( String.format("Couldn't compare '%s' to '%s'", property.toString(), test.toString())); } if (checkComparisonValue(node.getName(), comparisonValue)) { result.add(item); } } return result; case "like": case "match": propName = (String) node.getArgument(0); String matchString = (String) node.getArgument(1); Pattern matchPattern = Pattern.compile(matchString.replace("*", ".*"), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); result = new ArrayList<>(); for (T item : list) { Object property = getProperty(item, propName); String stringProperty; if (property instanceof String) { stringProperty = (String) property; } else { throw new UnsupportedOperationException( String.format("Property '%s' is not a string", propName)); } if (matchPattern.matcher(stringProperty).matches()) { result.add(item); } } return result; case "limit": int limit = (int) node.getArgument(0); int offset = node.getArgumentsSize() > 1 ? (int) node.getArgument(1) : 0; if (offset > list.size() - 1) { return Collections.emptyList(); } int toIndex = offset + limit; if (toIndex > list.size()) { toIndex = list.size(); } return list.subList(offset, toIndex); case "sort": ComparatorChain cc = new ComparatorChain(); for (Object obj : node) { String sortOption = (String) obj; boolean desc = sortOption.startsWith("-"); cc.addComparator(new BeanComparator<T>(sortOption.substring(1)), desc); } // copy the list as we are modifying it list = new ArrayList<>(list); Collections.sort(list, cc); return list; default: throw new UnsupportedOperationException( String.format("Encountered unknown operator '%s'", node.getName())); } }
From source file:org.gwtportlets.portlet.smartgwt.server.SmartComparator.java
/** * Compares two Field Comparable objects. * @param o1 The one object./*from w ww. ja v a 2 s . co m*/ * @param o2 The other object. * @return The comparison. */ public int compare(T o1, T o2) { for (SortSpecifierDto sort : sortArray) { Comparable v1, v2; try { v1 = reflection.getFieldValue(o1, sort.field); v2 = reflection.getFieldValue(o2, sort.field); } catch (SmartReflection.SmartReflectionException e) { log.error("Could not values for field \"" + sort.field + "\" for sorting comparison", e); return 0; } int value; if (v1 == null && v2 == null) { continue; } if (v1 == null) { value = -1; } else if (v2 == null) { value = 1; } else { value = v1.compareTo(v2); } if (!sort.isAscending) { value = -value; } if (value != 0) { return value; } } return 0; }
From source file:viper.api.time.TimeEncodedList.java
/** * {@inheritDoc}// ww w.j av a 2 s .co m */ public Comparable firstAfter(Comparable c) { SortedMap tail = values.tailMap(c); if (!tail.isEmpty()) { Iterator iter = tail.keySet().iterator(); Comparable a = (Comparable) iter.next(); if (a.compareTo(c) == 0) { if (iter.hasNext()) { a = (Comparable) iter.next(); } else { return null; } } return c; } return null; }
From source file:craterdog.collections.primitives.RandomizedTree.java
private int compareElements(E firstElement, E secondElement) { int comparison; if (comparator != null) { comparison = comparator.compare(firstElement, secondElement); } else {/*from www. j a v a 2s. c o m*/ @SuppressWarnings("unchecked") Comparable<E> comparable = (Comparable<E>) firstElement; // may throw ClassCastException comparison = comparable.compareTo(secondElement); } return comparison; }
From source file:com.redhat.rhn.common.util.DynamicComparator.java
/** * {@inheritDoc}// w w w. j ava 2s . c o m */ public int compare(Object o1, Object o2) { Comparable val1 = null; Comparable val2 = null; try { val1 = (Comparable) PropertyUtils.getProperty(o1, fieldName); val2 = (Comparable) PropertyUtils.getProperty(o2, fieldName); if (val1 instanceof String && val2 instanceof String) { return order * getCollator().compare(val1, val2); } // a < b = -1, a > b = 1 , a== b =0 if (val1 == null && val2 != null) { return order * -1; } else if (val1 != null && val2 == null) { return order * 1; } else if (val1 == val2) { return 0; } return order * val1.compareTo(val2); } catch (Exception e) { throw new IllegalArgumentException("Exception trying to compare " + "two objects: o1: " + o1 + " o2: " + o2 + " with field: " + this.fieldName + " generated this exception: " + e); } }