Java Code Examples for java.util.Comparator#compare()

The following examples show how to use java.util.Comparator#compare() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApiVersionComparator.java    From intellij-kubernetes with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: BTree.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
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.
}
 
Example 3
Source File: LLRBValueNode.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: SegmentRange.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    };
}
 
Example 5
Source File: AbstractSimplex.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: CombinationsTest.java    From hipparchus with Apache License 2.0 5 votes vote down vote up
@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});
}
 
Example 7
Source File: AbstractReadWriteAccess.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example 8
Source File: InsertionSorter.java    From 30-android-libraries-in-30-days with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 9
Source File: ArraySortTests.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: Interval.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/** 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;
}
 
Example 11
Source File: TypeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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!!");
    }
}
 
Example 12
Source File: AbstractAttributeInteraction.java    From constellation with Apache License 2.0 5 votes vote down vote up
@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;
        }
    };
}
 
Example 13
Source File: TreeMultiset.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
  }
}
 
Example 14
Source File: ComparisonPredicate.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
  });
}
 
Example 15
Source File: TrieMap_5Bits_Memoized_LazyHashCode.java    From oopsla15-artifact with Eclipse Public License 1.0 4 votes vote down vote up
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;
}
 
Example 16
Source File: Lists2.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 17
Source File: MediaComparators.java    From leafpicrevived with GNU General Public License v3.0 4 votes vote down vote up
private static <T> Comparator<T> reverse(Comparator<T> comparator) {
    return (o1, o2) -> comparator.compare(o2, o1);
}
 
Example 18
Source File: BinaryOperator.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: BinaryOperator.java    From openjdk-8 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: BinaryOperator.java    From JDKSourceCode1.8 with MIT License 2 votes vote down vote up
/**
 * 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;
}