当前位置: 首页>>代码示例>>Java>>正文


Java Comparator.compare方法代码示例

本文整理汇总了Java中java.util.Comparator.compare方法的典型用法代码示例。如果您正苦于以下问题:Java Comparator.compare方法的具体用法?Java Comparator.compare怎么用?Java Comparator.compare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Comparator的用法示例。


在下文中一共展示了Comparator.compare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: lowerBound

import java.util.Comparator; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:31,代码来源:Utils.java

示例2: deDuplicate

import java.util.Comparator; //导入方法依赖的package包/类
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;
}
 
开发者ID:tiweGH,项目名称:OpenDiabetes,代码行数:26,代码来源:ArraySort.java

示例3: selectionSort

import java.util.Comparator; //导入方法依赖的package包/类
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);
        }
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:25,代码来源:CoordinatorLayout.java

示例4: MergingIterator

import java.util.Comparator; //导入方法依赖的package包/类
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));
    }
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:22,代码来源:Iterators.java

示例5: testComparator

import java.util.Comparator; //导入方法依赖的package包/类
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);
                        }
                    }
                }
            }
        }
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:28,代码来源:DataFlavorComparatorTest1.java

示例6: count

import java.util.Comparator; //导入方法依赖的package包/类
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;
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:11,代码来源:TreeMultiset.java

示例7: equals

import java.util.Comparator; //导入方法依赖的package包/类
/**
 * 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;
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:15,代码来源:Attributes.java

示例8: heapSort

import java.util.Comparator; //导入方法依赖的package包/类
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();
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-SE-9-Road-to-Concurrent-and-High-Performance-Programming,代码行数:11,代码来源:ArrayHeap.java

示例9: main

import java.util.Comparator; //导入方法依赖的package包/类
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"));

	}
 
开发者ID:followwwind,项目名称:javase,代码行数:28,代码来源:Comparators.java

示例10: createColumnKeyIterator

import java.util.Comparator; //导入方法依赖的package包/类
/**
 * 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();
    }
  };
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:42,代码来源:TreeBasedTable.java

示例11: testExplicit_none

import java.util.Comparator; //导入方法依赖的package包/类
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);
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:12,代码来源:OrderingTest.java

示例12: testEqualsPerformance

import java.util.Comparator; //导入方法依赖的package包/类
@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");
    }
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:30,代码来源:ByteArrayWrapperTest.java

示例13: forCells

import java.util.Comparator; //导入方法依赖的package包/类
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);
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:34,代码来源:RegularImmutableTable.java

示例14: instancesLast

import java.util.Comparator; //导入方法依赖的package包/类
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;
        }
    };
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:14,代码来源:Comparators.java

示例15: forCells

import java.util.Comparator; //导入方法依赖的package包/类
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);
}
 
开发者ID:s-store,项目名称:s-store,代码行数:29,代码来源:RegularImmutableTable.java


注:本文中的java.util.Comparator.compare方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。