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

The following are Jave code examples for showing how to use compare() of the java.util.Comparator class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop-oss   File: Utils.java   View Source Code Vote up 6 votes
/**
 * Lower bound binary search. Find the index to the first element in the list
 * that compares greater than or equal to key.
 * 
 * @param <T>
 *          Type of the input key.
 * @param list
 *          The list
 * @param key
 *          The input key.
 * @param cmp
 *          Comparator for the key.
 * @return The index to the desired element if it exists; or list.size()
 *         otherwise.
 */
public static <T> int lowerBound(List<? extends T> list, T key,
    Comparator<? super T> cmp) {
  int low = 0;
  int high = list.size();

  while (low < high) {
    int mid = (low + high) >>> 1;
    T midVal = list.get(mid);
    int ret = cmp.compare(midVal, key);
    if (ret < 0)
      low = mid + 1;
    else high = mid;
  }
  return low;
}
 
Example 2
Project: OpenDiabetes   File: ArraySort.java   View Source Code Vote up 6 votes
public static int deDuplicate(Object[] array, int start, int limit,
                              Comparator comparator) {

    int baseIndex    = start;
    int currentIndex = start + 1;

    if (array.length == 0) {
        return 0;
    }

    for (; currentIndex < limit; currentIndex++) {
        int compare = comparator.compare(array[baseIndex],
                                         array[currentIndex]);

        if (compare == 0) {
            continue;
        }

        baseIndex++;

        array[baseIndex] = array[currentIndex];
    }

    return baseIndex + 1;
}
 
Example 3
Project: boohee_v5.6   File: CoordinatorLayout.java   View Source Code Vote up 6 votes
private static void selectionSort(List<View> list, Comparator<View> comparator) {
    if (list != null && list.size() >= 2) {
        int i;
        View[] array = new View[list.size()];
        list.toArray(array);
        for (i = 0; i < count; i++) {
            int min = i;
            for (int j = i + 1; j < count; j++) {
                if (comparator.compare(array[j], array[min]) < 0) {
                    min = j;
                }
            }
            if (i != min) {
                View minItem = array[min];
                array[min] = array[i];
                array[i] = minItem;
            }
        }
        list.clear();
        for (Object add : array) {
            list.add(add);
        }
    }
}
 
Example 4
Project: googles-monorepo-demo   File: Iterators.java   View Source Code Vote up 6 votes
public MergingIterator(
    Iterable<? extends Iterator<? extends T>> iterators,
    final Comparator<? super T> itemComparator) {
  // A comparator that's used by the heap, allowing the heap
  // to be sorted based on the top of each iterator.
  Comparator<PeekingIterator<T>> heapComparator =
      new Comparator<PeekingIterator<T>>() {
        @Override
        public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
          return itemComparator.compare(o1.peek(), o2.peek());
        }
      };

  queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator);

  for (Iterator<? extends T> iterator : iterators) {
    if (iterator.hasNext()) {
      queue.add(Iterators.peekingIterator(iterator));
    }
  }
}
 
Example 5
Project: jdk8u-jdk   File: DataFlavorComparatorTest1.java   View Source Code Vote up 5 votes
private static void testComparator(Comparator cmp, DataFlavor[] flavs)
        throws ClassNotFoundException {

    for (DataFlavor x: flavs) {
        for (DataFlavor y: flavs) {
            if (Math.signum(cmp.compare(x,y)) != -Math.signum(cmp.compare(y,x))) {
                throw new RuntimeException("Antisymmetry violated: " + x + ", " + y);
            }
            if (cmp.compare(x,y) == 0 && !x.equals(y)) {
                throw new RuntimeException("Equals rule violated: " + x + ", " + y);
            }
            for (DataFlavor z: flavs) {
                if (cmp.compare(x,y) == 0) {
                    if (Math.signum(cmp.compare(x, z)) != Math.signum(cmp.compare(y, z))) {
                        throw new RuntimeException("Transitivity (1) violated: " + x + ", " + y + ", " + z);
                    }
                } else {
                    if (Math.signum(cmp.compare(x, y)) == Math.signum(cmp.compare(y, z))) {
                        if (Math.signum(cmp.compare(x, y)) != Math.signum(cmp.compare(x, z))) {
                            throw new RuntimeException("Transitivity (2) violated: " + x + ", " + y + ", " + z);
                        }
                    }
                }
            }
        }
    }
}
 
Example 6
Project: googles-monorepo-demo   File: TreeMultiset.java   View Source Code Vote up 5 votes
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 7
Project: OpenJSharp   File: Attributes.java   View Source Code Vote up 5 votes
/**
 * Compares this attribute name to another for equality.
 * @param o the object to compare
 * @return true if this attribute name is equal to the
 *         specified attribute object
 */
public boolean equals(Object o) {
    if (o instanceof Name) {
        Comparator<String> c = ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER;
        return c.compare(name, ((Name)o).name) == 0;
    } else {
        return false;
    }
}
 
Example 8
Project: Java-SE-9-Road-to-Concurrent-and-High-Performance-Programming   File: ArrayHeap.java   View Source Code Vote up 5 votes
public static <E> void heapSort(E[] array, Comparator<E> comparator){
    ArrayHeap<E> arrayHeap = new ArrayHeap<E>(0, (a,b) -> comparator.compare(b,a));
    arrayHeap.store = array;
    for(int i=0;i<array.length;i++){
        arrayHeap.insert(array[i]);
    }
    for(int i=array.length-1;i>=0;i--){
        array[i] = arrayHeap.removeMin();
    }
}
 
Example 9
Project: javase   File: Comparators.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
		//可以简化成如下方式
//		Comparator<Person> comparator2 = (p1, p2) -> p1.getAge().compareTo(p2.getAge());

		Comparator<Person> comparator = Comparator.comparing(Person::getAge);
		Person pp1 = new Person("John", 18);
		Person pp2 = new Person("Alice", 20);
		
		
		    
		int c1 = comparator.compare(pp1, pp2);             // > 0   
		int c2 = comparator.reversed().compare(pp1, pp2);  // < 0  
		System.out.println("c1:" + c1 + "," + "c2:" + c2);
		
		
		List<Person> persons = Arrays.asList(pp1, pp2);
		
		Collections.sort(persons, comparator);
		persons.forEach(p -> System.out.print(p.getAge() + "\t"));
		System.out.println();
		Collections.sort(persons, (p1, p2) -> {
			int age = p2.getAge() - p1.getAge();
			return age > 0 ? 1 : (age == 0 ? 0 : -1);
		});
		persons.forEach(p -> System.out.print(p.getAge() + "\t"));

	}
 
Example 10
Project: guava-mock   File: TreeBasedTable.java   View Source Code Vote up 5 votes
/**
 * Overridden column iterator to return columns values in globally sorted
 * order.
 */
@Override
Iterator<C> createColumnKeyIterator() {
  final Comparator<? super C> comparator = columnComparator();

  final Iterator<C> merged =
      Iterators.mergeSorted(
          Iterables.transform(
              backingMap.values(),
              new Function<Map<C, V>, Iterator<C>>() {
                @Override
                public Iterator<C> apply(Map<C, V> input) {
                  return input.keySet().iterator();
                }
              }),
          comparator);

  return new AbstractIterator<C>() {
    C lastValue;

    @Override
    protected C computeNext() {
      while (merged.hasNext()) {
        C next = merged.next();
        boolean duplicate = lastValue != null && comparator.compare(next, lastValue) == 0;

        // Keep looping till we find a non-duplicate value.
        if (!duplicate) {
          lastValue = next;
          return lastValue;
        }
      }

      lastValue = null; // clear reference to unused data
      return endOfData();
    }
  };
}
 
Example 11
Project: guava-mock   File: OrderingTest.java   View Source Code Vote up 5 votes
public void testExplicit_none() {
  Comparator<Integer> c
      = Ordering.explicit(Collections.<Integer>emptyList());
  try {
    c.compare(0, 0);
    fail();
  } catch (IncomparableValueException expected) {
    assertEquals(0, expected.value);
  }
  reserializeAndAssert(c);
}
 
Example 12
Project: rskj   File: ByteArrayWrapperTest.java   View Source Code Vote up 5 votes
@Test
public void testEqualsPerformance() {
    boolean testEnabled = false;

    if (testEnabled) {
        final int ITERATIONS = 10000000;
        long start1 = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            Comparator<byte[]> comparator = UnsignedBytes
                    .lexicographicalComparator();

            comparator.compare(wrapper1.getData(),
                    wrapper2.getData());
        }
        System.out.println(System.currentTimeMillis() - start1 + "ms");

        long start2 = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            Arrays.equals(wrapper1.getData(), wrapper2.getData());
        }
        System.out.println(System.currentTimeMillis() - start2 + "ms");

        long start3 = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            FastByteComparisons.compareTo(wrapper1.getData(), 0, wrapper1.getData().length, wrapper2.getData(), 0, wrapper1.getData().length);
        }
        System.out.println(System.currentTimeMillis() - start3 + "ms");
    }
}
 
Example 13
Project: googles-monorepo-demo   File: RegularImmutableTable.java   View Source Code Vote up 5 votes
static <R, C, V> RegularImmutableTable<R, C, V> forCells(
    List<Cell<R, C, V>> cells,
    @Nullable final Comparator<? super R> rowComparator,
    @Nullable final Comparator<? super C> columnComparator) {
  checkNotNull(cells);
  if (rowComparator != null || columnComparator != null) {
    /*
     * This sorting logic leads to a cellSet() ordering that may not be expected and that isn't
     * documented in the Javadoc. If a row Comparator is provided, cellSet() iterates across the
     * columns in the first row, the columns in the second row, etc. If a column Comparator is
     * provided but a row Comparator isn't, cellSet() iterates across the rows in the first
     * column, the rows in the second column, etc.
     */
    Comparator<Cell<R, C, V>> comparator =
        new Comparator<Cell<R, C, V>>() {
          @Override
          public int compare(Cell<R, C, V> cell1, Cell<R, C, V> cell2) {
            int rowCompare =
                (rowComparator == null)
                    ? 0
                    : rowComparator.compare(cell1.getRowKey(), cell2.getRowKey());
            if (rowCompare != 0) {
              return rowCompare;
            }
            return (columnComparator == null)
                ? 0
                : columnComparator.compare(cell1.getColumnKey(), cell2.getColumnKey());
          }
        };
    Collections.sort(cells, comparator);
  }
  return forCellsInternal(cells, rowComparator, columnComparator);
}
 
Example 14
Project: ProjectAres   File: Comparators.java   View Source Code Vote up 5 votes
public static <T, U> Comparator<T> instancesLast(Class<U> type, Comparator<U> c) {
    return (a, b) -> {
        if(type.isInstance(a)) {
            if(type.isInstance(b)) {
                return c.compare(type.cast(a), type.cast(b));
            } else {
                return -1;
            }
        } else {
            return type.isInstance(b) ? 1 : 0;
        }
    };
}
 
Example 15
Project: s-store   File: RegularImmutableTable.java   View Source Code Vote up 5 votes
static <R, C, V> RegularImmutableTable<R, C, V> forCells(
    List<Cell<R, C, V>> cells,
    @Nullable final Comparator<? super R> rowComparator,
    @Nullable final Comparator<? super C> columnComparator) {
  checkNotNull(cells);
  if (rowComparator != null || columnComparator != null) {
    /*
     * This sorting logic leads to a cellSet() ordering that may not be expected and that isn't
     * documented in the Javadoc. If a row Comparator is provided, cellSet() iterates across the
     * columns in the first row, the columns in the second row, etc. If a column Comparator is
     * provided but a row Comparator isn't, cellSet() iterates across the rows in the first
     * column, the rows in the second column, etc.
     */
    Comparator<Cell<R, C, V>> comparator = new Comparator<Cell<R, C, V>>() {
      @Override public int compare(Cell<R, C, V> cell1, Cell<R, C, V> cell2) {
        int rowCompare = (rowComparator == null) ? 0
          : rowComparator.compare(cell1.getRowKey(), cell2.getRowKey());
        if (rowCompare != 0) {
          return rowCompare;
        }
        return (columnComparator == null) ? 0
            : columnComparator.compare(cell1.getColumnKey(), cell2.getColumnKey());
      }
    };
    Collections.sort(cells, comparator);
  }
  return forCellsInternal(cells, rowComparator, columnComparator);
}
 
Example 16
Project: lams   File: CompareToBuilder.java   View Source Code Vote up 4 votes
/**
 * <p>Appends to the <code>builder</code> the comparison of
 * two <code>Object</code>s.</p>
 *
 * <ol>
 * <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) {
            comparison = ((Comparable) lhs).compareTo(rhs);
        } else {
            comparison = comparator.compare(lhs, rhs);
        }
    }
    return this;
}
 
Example 17
Project: guava-mock   File: TreeBasedTable.java   View Source Code Vote up 4 votes
int compare(Object a, Object b) {
  // pretend we can compare anything
  @SuppressWarnings({"rawtypes", "unchecked"})
  Comparator<Object> cmp = (Comparator) comparator();
  return cmp.compare(a, b);
}
 
Example 18
Project: android-retrostreams   File: Comparators.java   View Source Code Vote up 3 votes
/**
 * Returns a lexicographic-order comparator with another comparator.
 * If the {@code this_} {@code Comparator} considers two elements equal, i.e.
 * {@code compare(a, b) == 0}, {@code other} is used to determine the order.
 *
 * <p>The returned comparator is serializable if the specified comparators
 * are also serializable.
 *
 * <p><b>API Note:</b><br>
 * For example, to sort a collection of {@code String} based on the length
 * and then case-insensitive natural ordering, the comparators can be
 * composed using following code,
 *
 * <pre>{@code
 *     Comparator<String> cmp = Comparators.thenComparing(Comparators.comparingInt(String::length),
 *                        String.CASE_INSENSITIVE_ORDER);
 * }</pre>
 *
 * @param <T> the type of objects that may be compared by the passed comparators
 * @param this_ the comparator to be used first
 * @param  other the other comparator to be used when the {@code this_} comparator
 *         compares two objects that are equal.
 * @return a lexicographic-order comparator composed of the {@code this_} and then the
 *         other comparator
 * @throws NullPointerException if {@code this_} is null.
 * @throws NullPointerException if {@code other} is null.
 * @since 1.8
 */
public static <T> Comparator<T> thenComparing(Comparator<? super T> this_, Comparator<? super T> other) {
    Objects.requireNonNull(this_);
    Objects.requireNonNull(other);
    if (this_ instanceof NullComparator) {
        return ((NullComparator<T>) this_).thenComparing(other);
    }
    return (Comparator<T> & Serializable) (c1, c2) -> {
        int res = this_.compare(c1, c2);
        return (res != 0) ? res : other.compare(c1, c2);
    };
}
 
Example 19
Project: quickhybrid-android   File: FileSorter.java   View Source Code Vote up 2 votes
/**
 * @param object1
 * @param object2
 * @return
 */
private int compareByName(File object1, File object2) {
    Comparator<Object> cmp = Collator.getInstance(java.util.Locale.CHINA);
    return cmp.compare(object1.getName(), object2.getName());
}
 
Example 20
Project: openjdk-jdk10   File: BinaryOperator.java   View Source Code Vote up 2 votes
/**
 * 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;
}