compare ( )源码实例Demo

java.util.Comparator#compare ( )源码实例Demo

下面列出了java.util.Comparator#compare ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: stratio-cassandra   文件: BTree.java
static <V> int find(Comparator<V> comparator, Object key, Object[] a, final int fromIndex, final int toIndex)
{
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high)
    {
        int mid = (low + high) / 2;
        int cmp = comparator.compare((V) key, (V) a[mid]);

        if (cmp > 0)
            low = mid + 1;
        else if (cmp < 0)
            high = mid - 1;
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found.
}
 
@Override
public int compare(final String o1, final String o2) {
    final Matcher matcherOne = VERSION_FORMAT_REGEX.matcher(o1);
    final Matcher matcherTwo = VERSION_FORMAT_REGEX.matcher(o2);

    // Fall back to simple string comparision if either of the versions cannot be parsed
    if (!matcherOne.matches() || !matcherTwo.matches()) {
        return o1.compareTo(o2);
    }

    Comparator<Matcher> comparator = Comparator.comparing(m -> m.group("group"), Comparator.nullsFirst(Comparator.naturalOrder()));
    comparator = comparator.thenComparingInt(m -> Integer.parseInt(m.group("major")));
    comparator = comparator.thenComparing(m -> m.group("minor"), Comparator.nullsLast(Comparator.naturalOrder()));

    return comparator.compare(matcherOne, matcherTwo);
}
 
源代码3 项目: firebase-admin-java   文件: LLRBValueNode.java
@Override
public LLRBNode<K, V> insert(K key, V value, Comparator<K> comparator) {
  int cmp = comparator.compare(key, this.key);
  LLRBValueNode<K, V> n;
  if (cmp < 0) {
    // new key is less than current key
    LLRBNode<K, V> newLeft = this.left.insert(key, value, comparator);
    n = copy(null, null, newLeft, null);
  } else if (cmp == 0) {
    // same key
    n = copy(key, value, null, null);
  } else {
    // new key is greater than current key
    LLRBNode<K, V> newRight = this.right.insert(key, value, comparator);
    n = copy(null, null, null, newRight);
  }
  return n.fixUp();
}
 
源代码4 项目: kylin-on-parquet-v2   文件: SegmentRange.java
public static Comparator<Endpoint> getComparator(final Comparator valueComparator) {
    return new Comparator<Endpoint>() {
        @Override
        public int compare(Endpoint a, Endpoint b) {
            if (a == null || b == null)
                throw new IllegalStateException();
            if (a.isMin) {
                return b.isMin ? 0 : -1;
            } else if (b.isMin) {
                return a.isMin ? 0 : 1;
            } else if (a.isMax) {
                return b.isMax ? 0 : 1;
            } else if (b.isMax) {
                return a.isMax ? 0 : -1;
            } else {
                return valueComparator.compare(a.v, b.v);
            }
        }
    };
}
 
源代码5 项目: Bats   文件: ComparisonPredicate.java
/**
 * LT (<) predicate.
 */
private static <C extends Comparable<C>> LogicalExpression createLTPredicate(
    LogicalExpression left, LogicalExpression right) {
  return new ComparisonPredicate<C>(left, right, (leftStat, rightStat) -> {
    Comparator<C> valueComparator = leftStat.getValueComparator();
    if (valueComparator.compare(getMaxValue(rightStat), getMinValue(leftStat)) <= 0) {
      return RowsMatch.NONE;
    }
    return valueComparator.compare(getMaxValue(leftStat), getMinValue(rightStat)) < 0 ? checkNull(leftStat, rightStat) : RowsMatch.SOME;
  });
}
 
源代码6 项目: codebuff   文件: TreeMultiset.java
public int count(Comparator<? super E> comparator, E e) {
  int cmp = comparator.compare(e, elem);
  if (cmp < 0) {
    return (left == null) ? 0 : left.count(comparator, e);
  } else if (cmp > 0) {
    return (right == null) ? 0 : right.count(comparator, e);
  } else {
    return elemCount;
  }
}
 
@SuppressWarnings("unchecked")
private Comparator<Object> createObjectComparator(final Comparator<T> comparator) {
    return (o1, o2) -> {
        try {
            return comparator.compare((T) o1, (T) o2);
        } catch (ClassCastException ex) {
            return 0;
        }
    };
}
 
源代码8 项目: openjdk-jdk9   文件: TypeTest.java
static <T> void assertOrder(T o1, T o2, Comparator<? super T> cmp) {
    if (cmp.compare(o1, o2) > 0) {
        System.out.println("Fail!!");
    }
    if (cmp.compare(o1, o2) == 0) {
        System.out.println("Equal!!");
    }
}
 
源代码9 项目: openjdk-8-source   文件: Interval.java
/** Routine which can be used instead of the one taking an interval,
    for the situation where the endpoints are being retrieved from
    different data structures */
public boolean overlaps(Object otherLowEndpoint,
                        Object otherHighEndpoint,
                        Comparator endpointComparator) {
  if (endpointComparator.compare(highEndpoint, otherLowEndpoint) <= 0) {
    return false;
  }
  if (endpointComparator.compare(lowEndpoint, otherHighEndpoint) >= 0) {
    return false;
  }
  return true;
}
 
源代码10 项目: morpheus-core   文件: ArraySortTests.java
@SuppressWarnings("unchecked")
static <T> boolean isDescending(Array<T> array, int start, int end) {
    Assert.assertTrue(array.length() > 1, "The array has elements");
    final Comparator<T> comparator = Comparators.getDefaultComparator(array.type());
    for (int i=start+1; i<end; ++i) {
        final T v1 = array.getValue(i-1);
        final T v2 = array.getValue(i);
        final int result = comparator.compare(v1, v2);
        if (result < 0) {
            System.out.println("Values are not in descending order at " + i);
            return false;
        }
    }
    return true;
}
 
@Override
public void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator) {
	for(int i = pStart + 1; i < pEnd; i++) {
		final T current = pList.get(i);
		T prev = pList.get(i - 1);
		if(pComparator.compare(current, prev) < 0) {
			int j = i;
			do {
				pList.set(j--, prev);
			} while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0);
			pList.set(j, current);
		}
	}
	return;
}
 
源代码12 项目: lams   文件: AbstractReadWriteAccess.java
@Override
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
	if ( DEBUG_ENABLED ) {
		log.debugf(
				"Checking writeability of read-write cache item [timestamp=`%s`, version=`%s`] : txTimestamp=`%s`, newVersion=`%s`",
				timestamp,
				version,
				txTimestamp,
				newVersion
		);
	}

	//noinspection unchecked
	return version != null && versionComparator.compare( version, newVersion ) < 0;
}
 
源代码13 项目: hipparchus   文件: CombinationsTest.java
@Test(expected=MathIllegalArgumentException.class)
public void testLexicographicComparatorWrongIterate3() {
    final int n = 5;
    final int k = 3;
    final Comparator<int[]> comp = new Combinations(n, k).comparator();
    comp.compare(new int[] {1, 2, 5}, new int[] {0, 1, 2});
}
 
源代码14 项目: astor   文件: AbstractSimplex.java
/**
 * Replace the worst point of the simplex by a new point.
 *
 * @param pointValuePair Point to insert.
 * @param comparator Comparator to use for sorting the simplex vertices
 * from best to worst.
 */
protected void replaceWorstPoint(PointValuePair pointValuePair,
                                 final Comparator<PointValuePair> comparator) {
    for (int i = 0; i < dimension; i++) {
        if (comparator.compare(simplex[i], pointValuePair) > 0) {
            PointValuePair tmp = simplex[i];
            simplex[i] = pointValuePair;
            pointValuePair = tmp;
        }
    }
    simplex[dimension] = pointValuePair;
}
 
源代码15 项目: leafpicrevived   文件: MediaComparators.java
private static <T> Comparator<T> reverse(Comparator<T> comparator) {
    return (o1, o2) -> comparator.compare(o2, o1);
}
 
CompactMapNode<K, V> removed(final AtomicReference<Thread> mutator, final K key,
				final int keyHash, final int shift, final MapResult<K, V> details,
				final Comparator<Object> cmp) {
	final int mask = mask(keyHash, shift);
	final int bitpos = bitpos(mask);

	if ((dataMap() & bitpos) != 0) { // inplace value
		final int dataIndex = dataIndex(bitpos);

		int currentKeyHash = getKeyHash(dataIndex);
		
		if (currentKeyHash == keyHash && cmp.compare(getKey(dataIndex), key) == 0) {
			final V currentVal = getValue(dataIndex);
			details.updated(currentVal);

			if (this.payloadArity() == 2 && this.nodeArity() == 0) {
				/*
				 * Create new node with remaining pair. The new node
				 * will a) either become the new root returned, or b)
				 * unwrapped and inlined during returning.
				 */
				final int newDataMap = (shift == 0) ? (int) (dataMap() ^ bitpos)
								: bitpos(mask(keyHash, 0));

				if (dataIndex == 0) {
					return CompactMapNode.nodeOf(mutator, (int) (0), newDataMap,
							new Object[] { getKey(1), getValue(1) },
							new int[] { getKeyHash(1) });
				} else {
					return CompactMapNode.nodeOf(mutator, (int) (0), newDataMap,
							new Object[] { getKey(0), getValue(0) },
							new int[] { getKeyHash(0) });
				}
			} else {
				return copyAndRemoveValue(mutator, bitpos);
			}
		} else {
			return this;
		}
	} else if ((nodeMap() & bitpos) != 0) { // node (not value)
		final CompactMapNode<K, V> subNode = nodeAt(bitpos);
		final CompactMapNode<K, V> subNodeNew = subNode.removed(mutator, key, keyHash,
						shift + BIT_PARTITION_SIZE, details, cmp);

		if (!details.isModified()) {
			return this;
		}

		switch (subNodeNew.sizePredicate()) {
		case 0: {
			throw new IllegalStateException("Sub-node must have at least one element.");
		}
		case 1: {
			if (this.payloadArity() == 0 && this.nodeArity() == 1) {
				// escalate (singleton or empty) result
				return subNodeNew;
			} else {
				// inline value (move to front)
				return copyAndMigrateFromNodeToInline(mutator, bitpos, subNodeNew);
			}
		}
		default: {
			// modify current node (set replacement node)
			return copyAndSetNode(mutator, bitpos, subNodeNew);
		}
		}
	}

	return this;
}
 
源代码17 项目: crate   文件: Lists2.java
/**
 * Finds the first non peer element in the provided list of items between the begin and end indexes.
 * Two items are peers if the provided comparator designates them as equals.
 * @return the position of the first item that's not equal with the item on the `begin` index in the list of items.
 */
public static <T> int findFirstNonPeer(List<T> items, int begin, int end, @Nullable Comparator<T> cmp) {
    if (cmp == null || (begin + 1) >= end) {
        return end;
    }
    T fst = items.get(begin);
    if (cmp.compare(fst, items.get(begin + 1)) != 0) {
        return begin + 1;
    }
    /*
     * Adapted binarySearch algorithm to find the first non peer (instead of the first match)
     * This depends on there being at least some EQ values;
     * Whenever we find a EQ pair we check if the following element isn't EQ anymore.
     *
     * E.g.
     *
     * i:     0  1  2  3  4  5  6  7
     * rows: [1, 1, 1, 1, 4, 4, 5, 6]
     *        ^ [1  1  1  4  4  5  6]
     *        +-----------^
     *           cmp: -1
     *        1 [1  1  1  4] 4  5  6
     *        ^     ^
     *        +-----+
     *           cmp: 0 --> cmp (mid +1) != 0 --> false
     *        1  1  1 [1  4] 4  5  6
     *        ^        ^
     *        +--------+
     *           cmp: 0 --> cmp (mid +1) != 0 --> true
     */
    int low = begin + 1;
    int high = end;
    while (low <= high) {
        int mid = (low + high) >>> 1;
        T t = items.get(mid);
        int cmpResult = cmp.compare(fst, t);
        if (cmpResult == 0) {
            int next = mid + 1;
            if (next == high || cmp.compare(fst, items.get(next)) != 0) {
                return next;
            } else {
                low = next;
            }
        } else if (cmpResult < 0) {
            high = mid;
        } else {
            low = mid;
        }
    }
    return end;
}
 
源代码18 项目: JDKSourceCode1.8   文件: BinaryOperator.java
/**
 * Returns a {@link BinaryOperator} which returns the lesser of two elements
 * according to the specified {@code Comparator}.
 *
 * @param <T> the type of the input arguments of the comparator
 * @param comparator a {@code Comparator} for comparing the two values
 * @return a {@code BinaryOperator} which returns the lesser of its operands,
 *         according to the supplied {@code Comparator}
 * @throws NullPointerException if the argument is null
 */
public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
    Objects.requireNonNull(comparator);
    return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
}
 
源代码19 项目: j2objc   文件: BinaryOperator.java
/**
 * Returns a {@link BinaryOperator} which returns the greater of two elements
 * according to the specified {@code Comparator}.
 *
 * @param <T> the type of the input arguments of the comparator
 * @param comparator a {@code Comparator} for comparing the two values
 * @return a {@code BinaryOperator} which returns the greater of its operands,
 *         according to the supplied {@code Comparator}
 * @throws NullPointerException if the argument is null
 */
public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
    Objects.requireNonNull(comparator);
    return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
}
 
源代码20 项目: openjdk-8   文件: BinaryOperator.java
/**
 * Returns a {@link BinaryOperator} which returns the lesser of two elements
 * according to the specified {@code Comparator}.
 *
 * @param <T> the type of the input arguments of the comparator
 * @param comparator a {@code Comparator} for comparing the two values
 * @return a {@code BinaryOperator} which returns the lesser of its operands,
 *         according to the supplied {@code Comparator}
 * @throws NullPointerException if the argument is null
 */
public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
    Objects.requireNonNull(comparator);
    return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
}