Java Code Examples for java.util.Comparator

The following are top voted examples for showing how to use java.util.Comparator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: couchmove   File: FileUtils.java   Source Code and License 8 votes vote down vote up
/**
 * If the file is a Directory, calculate the checksum of all files in this directory (one level)
 * Else, calculate the checksum of the file matching extensions
 *
 * @param filePath   file or folder
 * @param extensions of files to calculate checksum of
 * @return checksum
 */
public static String calculateChecksum(@NotNull Path filePath, String... extensions) {
    if (filePath == null || !Files.exists(filePath)) {
        throw new CouchmoveException("File is null or doesn't exists");
    }
    if (Files.isDirectory(filePath)) {
        return directoryStream(filePath, extensions)
                .sorted(Comparator.comparing(path -> path.getFileName().toString()))
                .map(FileUtils::calculateChecksum)
                .reduce(String::concat)
                .map(DigestUtils::sha256Hex)
                .orElse(null);
    }
    try {
        return DigestUtils.sha256Hex(toByteArray(filePath.toUri()));
    } catch (IOException e) {
        throw new CouchmoveException("Unable to calculate file checksum '" + filePath.getFileName().toString() + "'");
    }
}
 
Example 2
Project: guava-mock   File: ImmutableSortedSet.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an immutable sorted set containing the given elements sorted by
 * the given {@code Comparator}. When multiple elements are equivalent
 * according to {@code compare()}, only the first one specified is
 * included. This method iterates over {@code elements} at most once.
 *
 * <p>Despite the method name, this method attempts to avoid actually copying
 * the data when it is safe to do so. The exact circumstances under which a
 * copy will or will not be performed are undocumented and subject to change.
 *
 * @throws NullPointerException if {@code comparator} or any of {@code
 *         elements} is null
 */
public static <E> ImmutableSortedSet<E> copyOf(
    Comparator<? super E> comparator, Iterable<? extends E> elements) {
  checkNotNull(comparator);
  boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);

  if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
    @SuppressWarnings("unchecked")
    ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
    if (!original.isPartialView()) {
      return original;
    }
  }
  @SuppressWarnings("unchecked") // elements only contains E's; it's safe.
  E[] array = (E[]) Iterables.toArray(elements);
  return construct(comparator, array.length, array);
}
 
Example 3
Project: jetfuel   File: SortNode.java   Source Code and License 6 votes vote down vote up
public final Comparator<Object[]> createObjectArrayComparator() {
	return new Comparator<Object[]>() {
		final int ordinal = column.getColumnIndex();

		@SuppressWarnings({ "rawtypes", "unchecked" })
		public int compare(Object[] left, Object[] right) {
			int ascSort = 0;
			Object a = left[ordinal];
			Object b = right[ordinal];
			if (a == null)
				ascSort = (b == null)
						? 0
						: 1;
			else if (b == null)
				ascSort = -1;
			else
				ascSort = ((Comparable) a).compareTo(b);
			return direction == SortDirection.ASC
					? ascSort
					: -ascSort;
		}
	};
}
 
Example 4
Project: googles-monorepo-demo   File: UnsignedBytesTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testLexicographicalComparatorLongInputs() {
  for (Comparator<byte[]> comparator : Arrays.asList(
      UnsignedBytes.lexicographicalComparator(),
      UnsignedBytes.lexicographicalComparatorJavaImpl())) {
    for (int i = 0; i < 32; i++) {
      byte[] left = new byte[32];
      byte[] right = new byte[32];

      assertTrue(comparator.compare(left, right) == 0);
      left[i] = 1;
      assertTrue(comparator.compare(left, right) > 0);
      assertTrue(comparator.compare(right, left) < 0);
    }
  }
}
 
Example 5
Project: googles-monorepo-demo   File: TreeMultisetTest.java   Source Code and License 6 votes vote down vote up
public void testCustomComparator() throws Exception {
  Comparator<String> comparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
      return o2.compareTo(o1);
    }
  };
  TreeMultiset<String> ms = TreeMultiset.create(comparator);

  ms.add("b");
  ms.add("c");
  ms.add("a");
  ms.add("b");
  ms.add("d");

  assertThat(ms).containsExactly("d", "c", "b", "b", "a").inOrder();

  SortedSet<String> elementSet = ms.elementSet();
  assertEquals("d", elementSet.first());
  assertEquals("a", elementSet.last());
  assertEquals(comparator, elementSet.comparator());
}
 
Example 6
Project: CustomWorldGen   File: PersistentRegistryManager.java   Source Code and License 6 votes vote down vote up
public static void fireRegistryEvents()
{
    List<ResourceLocation> registryKeys = Lists.newArrayList(PersistentRegistry.ACTIVE.registries.keySet());
    Collections.sort(registryKeys, new Comparator<ResourceLocation>()
    {
        @Override
        public int compare(ResourceLocation o1, ResourceLocation o2)
        {
            return o1.toString().compareToIgnoreCase(o2.toString());
        }
    });
    fireRegistryEvent(PersistentRegistry.ACTIVE.registries, BLOCKS);
    ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // inject any blocks
    fireRegistryEvent(PersistentRegistry.ACTIVE.registries, ITEMS);
    ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // inject any items
    for (ResourceLocation rl : registryKeys) {
        if (rl == BLOCKS || rl == ITEMS) continue;
        fireRegistryEvent(PersistentRegistry.ACTIVE.registries, rl);
    }
    ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // inject everything else
}
 
Example 7
Project: r8   File: MinifiedNameMapPrinter.java   Source Code and License 6 votes vote down vote up
private void write(DexProgramClass clazz, PrintStream out) {
  seenTypes.add(clazz.type);
  DexString descriptor = namingLens.lookupDescriptor(clazz.type);
  out.print(DescriptorUtils.descriptorToJavaType(clazz.type.descriptor.toSourceString()));
  out.print(" -> ");
  out.print(DescriptorUtils.descriptorToJavaType(descriptor.toSourceString()));
  out.println(":");
  write(sortedCopy(
      clazz.instanceFields(), Comparator.comparing(DexEncodedField::toSourceString)), out);
  write(sortedCopy(
      clazz.staticFields(), Comparator.comparing(DexEncodedField::toSourceString)), out);
  write(sortedCopy(
      clazz.directMethods(), Comparator.comparing(DexEncodedMethod::toSourceString)), out);
  write(sortedCopy(
      clazz.virtualMethods(), Comparator.comparing(DexEncodedMethod::toSourceString)), out);
}
 
Example 8
Project: azure-libraries-for-java   File: CosmosDBAccountImpl.java   Source Code and License 6 votes vote down vote up
private void ensureFailoverIsInitialized() {
    if (this.isInCreateMode()) {
        return;
    }

    if (!this.hasFailoverPolicyChanges) {
        this.failoverPolicies.clear();
        FailoverPolicyInner[] policyInners = new FailoverPolicyInner[this.inner().failoverPolicies().size()];
        this.inner().failoverPolicies().toArray(policyInners);
        Arrays.sort(policyInners, new Comparator<FailoverPolicyInner>() {
            @Override
            public int compare(FailoverPolicyInner o1, FailoverPolicyInner o2) {
                return o1.failoverPriority().compareTo(o2.failoverPriority());
            }
        });

        for (int i = 0; i < policyInners.length; i++) {
            this.failoverPolicies.add(policyInners[i]);
        }

        this.hasFailoverPolicyChanges = true;
    }
}
 
Example 9
Project: openjdk-jdk10   File: DefaultMXBeanMappingFactory.java   Source Code and License 6 votes vote down vote up
@Override
final Object toNonNullOpenValue(Object value)
        throws OpenDataException {
    final Collection<?> valueCollection = (Collection<?>) value;
    if (valueCollection instanceof SortedSet<?>) {
        Comparator<?> comparator =
            ((SortedSet<?>) valueCollection).comparator();
        if (comparator != null) {
            final String msg =
                "Cannot convert SortedSet with non-null comparator: " +
                comparator;
            throw openDataException(msg, new IllegalArgumentException(msg));
        }
    }
    final Object[] openArray = (Object[])
        Array.newInstance(getOpenClass().getComponentType(),
                          valueCollection.size());
    int i = 0;
    for (Object o : valueCollection)
        openArray[i++] = elementMapping.toOpenValue(o);
    return openArray;
}
 
Example 10
Project: googles-monorepo-demo   File: ImmutableSortedSet.java   Source Code and License 6 votes vote down vote up
private static <E> ImmutableSortedSet<E> copyOfInternal(
    Comparator<? super E> comparator, Iterable<? extends E> elements,
    boolean fromSortedSet) {
  checkNotNull(comparator);

  boolean hasSameComparator
      = fromSortedSet || hasSameComparator(elements, comparator);
  if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
    @SuppressWarnings("unchecked")
    ImmutableSortedSet<E> result = (ImmutableSortedSet<E>) elements;
    boolean isSubset = (result instanceof RegularImmutableSortedSet)
        && ((RegularImmutableSortedSet) result).isSubset;
    if (!isSubset) {
      // Only return the original copy if this immutable sorted set isn't
      // a subset of another, to avoid memory leak.
      return result;
    }
  }
  return copyOfInternal(comparator, elements.iterator());
}
 
Example 11
Project: Catter2   File: FavoritesActivity.java   Source Code and License 6 votes vote down vote up
private void updateFavorites(SharedPreferences pref) {
    String prefKey = String.format(SP_USER_FAVORITES_KEY, userToken);
    Log.d(TAG, "PrefKey: " + prefKey);
    Set<String> entriesSet = pref.getStringSet(prefKey, new HashSet<String>());

    ArrayList<FavoriteModel> favorites = new ArrayList<>(entriesSet.size());
    for (String entry : entriesSet) {
        String[] decoded = entry.split(";");
        favorites.add(new FavoriteModel(Long.valueOf(decoded[1]), decoded[0]));
    }

    Collections.sort(favorites, new Comparator<FavoriteModel>() {
        @Override
        public int compare(FavoriteModel o1, FavoriteModel o2) {
            return (int) (o2.getTimeAdded() - o1.getTimeAdded());
        }
    });

    ArrayList<String> urlsSorted = new ArrayList<>(favorites.size());
    for (FavoriteModel favorite : favorites) {
        urlsSorted.add(favorite.getUrl());
    }

    Log.d(TAG, "Updated favorites: " + urlsSorted.toString());
    rvAdapter.updateImageUrls(new ArrayList<>(urlsSorted));
}
 
Example 12
Project: mycat-src-1.6.1-RELEASE   File: TimSort.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a TimSort instance to maintain the state of an ongoing sort.
 *
 * @param a the array to be sorted
 * @param c the comparator to determine the order of the sort
 */
private SortState(Buffer a, Comparator<? super K> c, int len) {
  this.aLength = len;
  this.a = a;
  this.c = c;

  // Allocate temp storage (which may be increased later if necessary)
  tmpLength = len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
  tmp = s.allocate(tmpLength);

  /*
   * Allocate runs-to-be-merged stack (which cannot be expanded).  The
   * stack length requirements are described in listsort.txt.  The C
   * version always uses the same stack length (85), but this was
   * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
   * 100 elements) in Java.  Therefore, we use smaller (but sufficiently
   * large) stack lengths for smaller arrays.  The "magic numbers" in the
   * computation below must be changed if MIN_MERGE is decreased.  See
   * the MIN_MERGE declaration above for more information.
   */
  int stackLen = (len <    120  ?  5 :
                  len <   1542  ? 10 :
                  len < 119151  ? 19 : 40);
  runBase = new int[stackLen];
  runLen = new int[stackLen];
}
 
Example 13
Project: FreeCol   File: Colony.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Unit getDefendingUnit(Unit attacker) {
    if (displayUnitCount > 0) {
        // There are units, but we don't see them
        return null;
    }

    // Note that this function will only return a unit working
    // inside the colony.  Typically, colonies are also defended
    // by units outside the colony on the same tile.  To consider
    // units outside the colony as well, use
    // @see Tile#getDefendingUnit instead.
    final CombatModel cm = getGame().getCombatModel();
    final Comparator<Unit> comp
            = cachingDoubleComparator(u -> cm.getDefencePower(attacker, u));
    return maximize(getUnits(), comp);
}
 
Example 14
Project: MoodSwings   File: MoodList.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @return
 *
 * Get the most recent mood from the end of the sorted array.
 */
public MoodEvent getMostRecent() {
    Collections.sort(moodEvents, new Comparator<MoodEvent>() {
        public int compare(MoodEvent mood1, MoodEvent mood2) {
            long t1 = 0;
            long t2 = 0;
            try {
                t1 = COMBINED_DATE_FORMAT.parse(
                        String.format("%1$s %2$s", mood1.getDate(), mood1.getTime()))
                        .getTime();
                t2 = COMBINED_DATE_FORMAT.parse(
                        String.format("%1$s %2$s", mood2.getDate(), mood2.getTime()))
                        .getTime();
            } catch (ParseException e) {
                return 1;
            }
            return Long.valueOf(t2).compareTo(t1);
        }
    });
    return getMoodEvent(0);//(moodEvents.size() - 1);
}
 
Example 15
Project: s-store   File: Range.java   Source Code and License 6 votes vote down vote up
/**
 * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in
 * this range.
 */
public boolean containsAll(Iterable<? extends C> values) {
  if (Iterables.isEmpty(values)) {
    return true;
  }

  // this optimizes testing equality of two range-backed sets
  if (values instanceof SortedSet) {
    SortedSet<? extends C> set = cast(values);
    Comparator<?> comparator = set.comparator();
    if (Ordering.natural().equals(comparator) || comparator == null) {
      return contains(set.first()) && contains(set.last());
    }
  }

  for (C value : values) {
    if (!contains(value)) {
      return false;
    }
  }
  return true;
}
 
Example 16
Project: FreeCol   File: DebugUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Debug action to change the roles of a unit.
 *
 * Called from tile popup menu.
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 * @param unit The {@code Unit} to change the role of.
 */
public static void changeRole(final FreeColClient freeColClient,
                              final Unit unit) {
    final FreeColServer server = freeColClient.getFreeColServer();
    final Game sGame = server.getGame();
    final Unit sUnit = sGame.getFreeColGameObject(unit.getId(), Unit.class);
    final GUI gui = freeColClient.getGUI();
    final Function<Role, ChoiceItem<Role>> roleMapper = r ->
        new ChoiceItem<Role>(r.getId(), r);

    Role roleChoice = gui.getChoice(null,
        StringTemplate.template("prompt.selectRole"), "cancel",
        transform(sGame.getSpecification().getRoles(), alwaysTrue(),
                  roleMapper, Comparator.naturalOrder()));
    if (roleChoice == null) return;

    sUnit.changeRole(roleChoice, roleChoice.getMaximumCount());
    reconnect(freeColClient);
}
 
Example 17
Project: PrivacyStreams   File: ByFieldStreamSorter.java   Source Code and License 5 votes vote down vote up
@Override
protected void reorder(List<Item> items) {
    Collections.sort(items, new Comparator<Item>() {
        @Override
        public int compare(Item item1, Item item2) {
            Comparable value1 = item1.getValueByField(fieldToSort);
            Comparable value2 = item2.getValueByField(fieldToSort);
            return value1.compareTo(value2);
        }
    });
}
 
Example 18
Project: lib-commons-httpclient   File: TestCookiePathComparator.java   Source Code and License 5 votes vote down vote up
public void testEquality2() {
    Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/", null, false); 
    Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false);
    Comparator comparator = new CookiePathComparator();
    assertTrue(comparator.compare(cookie1, cookie2) == 0);
    assertTrue(comparator.compare(cookie2, cookie1) == 0);
}
 
Example 19
Project: alevin-svn2   File: FullKnowledgeClusterHead.java   Source Code and License 5 votes vote down vote up
@Override
public Collection<ClusterHead> findClusterCandidates(final VirtualNetwork vNetwork, ClusterHead orig) {

	LinkedList<FullKnowledgeClusterHead> result = new LinkedList<FullKnowledgeClusterHead>();
	LinkedList<LockTree> queue = new LinkedList<LockTree>();
	
	if (!subLockTree.isFullyLocked()) {
		queue.add(subLockTree);
	}

	while (!queue.isEmpty()) {
		LockTree current = queue.pop();
		if (current.getChildren() != null) {
			for (LockTree t : current.getChildren()) {
				//TODO: Here we got Information of Children without sending a message!
				if (estimationAlgorithm.estimate(
						((FullKnowledgeClusterHead) t.getClusterHead()).getCluster(), vNetwork) >= 1.0d) {
					if (t.isUnLocked()) {
						queue.addLast(t);
					}
				}
			}
		}
		if (current.getClusterHead() != orig) {
			result.add((FullKnowledgeClusterHead) current.getClusterHead());
		}
	}

	Collections.sort(result, new Comparator<FullKnowledgeClusterHead>() {
		@Override
		public int compare(FullKnowledgeClusterHead o1, FullKnowledgeClusterHead o2) {
			
			double i1 = estimationAlgorithm.estimate(o1.getCluster(), vNetwork);
			double i2 = estimationAlgorithm.estimate(o2.getCluster(), vNetwork);
			
			if (i1 < i2) {
				return -1;
			}
			if (i1 > i2) {
				return 1;
			}
			
			return 0;
		}
	});

	return new LinkedList<ClusterHead>(result);
}
 
Example 20
Project: incubator-netbeans   File: TableSorter.java   Source Code and License 5 votes vote down vote up
/**
 * Sets comparator that will be used to compare values in the specified column. Note that the Comparator will obtain
 * row indices (as Integer objects) to compare and NOT actual cell values.
 * 
 * @param column model index of the column to be sorted 
 * @param comparator comparator that will sort the given column
 */ 
public void setColumnComparator(int column, Comparator comparator) {
    if (comparator == null) {
        columnComparators.remove(Integer.valueOf(column));
    } else {
        columnComparators.put(Integer.valueOf(column), comparator);
    }
}
 
Example 21
Project: cyberduck   File: AttributedList.java   Source Code and License 5 votes vote down vote up
/**
 * The CopyOnWriteArrayList iterator does not support remove but the sort implementation
 * makes use of it. Provide our own implementation here to circumvent.
 *
 * @param comparator The comparator to use
 * @see java.util.Collections#sort(java.util.List, java.util.Comparator)
 * @see java.util.concurrent.CopyOnWriteArrayList#iterator()
 */
private void doSort(final Comparator<E> comparator) {
    if(null == comparator) {
        return;
    }
    if(log.isDebugEnabled()) {
        log.debug(String.format("Sort list %s with comparator %s", this, comparator));
    }
    Collections.sort(impl, comparator);
}
 
Example 22
Project: parabuild-ci   File: SortedMap.java   Source Code and License 5 votes vote down vote up
public SortedMap(SessionImplementor session, CollectionPersister persister, Comparator comparator, Serializable disassembled, Object owner)
throws HibernateException {
	super(session);
	this.comparator=comparator;
	beforeInitialize(persister);
	Serializable[] array = (Serializable[]) disassembled;
	for (int i=0; i<array.length; i+=2 ) map.put(
		persister.getIndexType().assemble( array[i], session, owner ),
		persister.getElementType().assemble( array[i+1], session, owner )
	);
	setInitialized();
}
 
Example 23
Project: BrainControl   File: StrategyStorage.java   Source Code and License 5 votes vote down vote up
/**
 * Sorts a given list of strategies based on their successRate
 * 
 * @param strategyList the list of strategies to be sorted
 * @return the sorted list of strategies
 */
private ArrayList<Strategy> sortStrategies(ArrayList<Strategy> strategyList){
	Collections.sort(strategyList, new Comparator<Strategy>() 
	{
	    @Override
	    public int compare(Strategy s, Strategy t) 
	    {
	        return (int)(s.getSuccessRate() - t.getSuccessRate());
	    }
	});	
	return strategyList;
}
 
Example 24
Project: AquamarineLake   File: Lambda.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
{
	int a = 4;
	int b = 3;
	
	Comparator<Integer> xd = (x, y) -> {
		if (x > y) return -1;
		if (x == y) return 0;
		if (x < y) return 1;
		return -2;
	};
	
	System.out.println(xd.compare(a, b));
	
}
 
Example 25
Project: featurea   File: TimSort.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("fallthrough")
private static <T> void binarySort(T[] a, int lo, int hi, int start, Comparator<? super T> c) {
    if (DEBUG) assert lo <= start && start <= hi;
    if (start == lo) start++;
    for (; start < hi; start++) {
        T pivot = a[start];
        int left = lo;
        int right = start;
        if (DEBUG) assert left <= right;
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (c.compare(pivot, a[mid]) < 0) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        if (DEBUG) assert left == right;
        int n = start - left;
        switch (n) {
            case 2:
                a[left + 2] = a[left + 1];
            case 1:
                a[left + 1] = a[left];
                break;
            default:
                System.arraycopy(a, left, a, left + 1, n);
        }
        a[left] = pivot;
    }
}
 
Example 26
Project: alfresco-repository   File: VersionHistoryImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "deprecation" })
private void readObject(ObjectInputStream is) throws ClassNotFoundException, IOException
{
    GetField fields = is.readFields();
    if (fields.defaulted("versionsByLabel"))
    {
        // This is a V2.2 class
        // The old 'rootVersion' maps to the current 'rootVersion'
        this.versionsByLabel = (HashMap<String, Version>) fields.get("versions", new HashMap<String, Version>());
        // The old 'versionHistory' maps to the current 'versionHistory'
        this.versionHistory = (HashMap<String, String>) fields.get("versionHistory", new HashMap<String, String>());
        // Need this comparator as versionsByLabel is not a LinkedHashMap in this version 
        this.versionComparatorDesc = new VersionLabelComparator(); 
    }
    else if (fields.defaulted("versionComparatorDesc"))
    {
        // This is a V3.1.0 class
        // The old 'rootVersion' maps to the current 'rootVersion'
        this.versionsByLabel = (HashMap<String, Version>) fields.get("versionsByLabel", new HashMap<String, Version>());
        // The old 'versionHistory' maps to the current 'versionHistory'
        this.versionHistory = (HashMap<String, String>) fields.get("versionHistory", new HashMap<String, String>());
        // Need this comparator as versionsByLabel is not a LinkedHashMap in this version 
        this.versionComparatorDesc = new VersionLabelComparator(); 
    }
    else
    {
        // This is a V4.1.3 (and 4.0.2 HF) class
        // The old 'rootVersion' maps to the current 'rootVersion'
        this.versionsByLabel = (Map<String, Version>) fields.get("versionsByLabel", new LinkedHashMap<String, Version>());
        // The old 'versionHistory' maps to the current 'versionHistory'
        this.versionHistory = (HashMap<String, String>) fields.get("versionHistory", new HashMap<String, String>());
        this.versionComparatorDesc = (Comparator<Version>) fields.get("versionComparatorDesc", null); 
    }
}
 
Example 27
Project: android-retrostreams   File: Spliterators.java   Source Code and License 5 votes vote down vote up
private static <T> Spliterator<T> setSpliterator(Set<? extends T> c, String name) {
    if (!IS_HARMONY_ANDROID && NATIVE_SPECIALIZATION) {
        if ("java.util.HashMap$EntrySet".equals(name)) {
            return (Spliterator<T>) HMSpliterators
                    .<Object, Object> getEntrySetSpliterator((Set<Map.Entry<Object, Object>>) c);
        }
        if ("java.util.HashMap$KeySet".equals(name)) {
            return HMSpliterators.getKeySetSpliterator((Set<T>) c);
        }
    }

    if (c instanceof LinkedHashSet) {
        return spliterator(c, Spliterator.DISTINCT | Spliterator.ORDERED);
    }

    if (!IS_HARMONY_ANDROID && NATIVE_SPECIALIZATION) {
        if (c instanceof HashSet) {
            return HMSpliterators.getHashSetSpliterator((HashSet<T>) c);
        }
    }

    // default from j.u.SortedSet
    if (c instanceof SortedSet) {
        return new IteratorSpliterator<T>(c, Spliterator.DISTINCT
                | Spliterator.SORTED | Spliterator.ORDERED) {
            @Override
            public Comparator<? super T> getComparator() {
                return ((SortedSet<T>) c).comparator();
            }
        };
    }

    if ((NATIVE_SPECIALIZATION || IS_ANDROID) && c instanceof CopyOnWriteArraySet) {
        return COWArraySetSpliterator
                .spliterator((CopyOnWriteArraySet<T>) c);
    }

    // default from j.u.Set
    return Spliterators.spliterator(c, Spliterator.DISTINCT);
}
 
Example 28
Project: FlashLib   File: CvProcessing.java   Source Code and License 5 votes vote down vote up
/**
 * Sorts the contours by their size and removes contours for the bottom of the list if the list contains
 * too many contours. 
 * 
 * @param contours list of contours
 * @param amount the maximum amount of contours that should remain after the operation
 * @see #filterByComparator(List, int, Comparator)
 */
public static void filterForSmallestContours(List<MatOfPoint> contours, int amount){
	Comparator<MatOfPoint> sizeComparer = (MatOfPoint o1, MatOfPoint o2) ->{
		if(o1.total() > o2.total()) return 1;
		else if(o2.total() > o1.total()) return -1;
		return 0;
	};
	filterByComparator(contours, amount, sizeComparer);
}
 
Example 29
Project: Cognizant-Intelligent-Test-Scripter   File: ORUtils.java   Source Code and License 5 votes vote down vote up
public static void sort(ORRootInf root) {
    Collections.sort(root.getPages(), new Comparator<ORPageInf>() {
        @Override
        public int compare(ORPageInf t, ORPageInf t1) {
            return t.getName().compareToIgnoreCase(t1.getName());
        }
    });
}
 
Example 30
Project: s-store   File: HistogramUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the list of values sorted in descending order by cardinality
 * @param h
 * @return
 */
public static <X> Collection<X> sortedValues(final Histogram<X> h) {
    SortedSet<X> sorted = new TreeSet<X>(new Comparator<X>() {
        public int compare(final X item0, final X item1) {
            final Long v0 = h.get(item0);
            final Long v1 = h.get(item1);
            if (v0.equals(v1))
                return (-1);
            return (v1.compareTo(v0));
          }
    });
    sorted.addAll(h.values());
    return (sorted);
}
 
Example 31
Project: guava-mock   File: SetsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Utility method to verify that the given SortedSet is equal to and
 * hashes identically to a set constructed with the elements in the
 * given iterable.  Also verifies that the comparator is the same as the
 * given comparator.
 */
private static <E> void verifySortedSetContents(
    SortedSet<E> set, Iterable<E> iterable,
    @Nullable Comparator<E> comparator) {
  assertSame(comparator, set.comparator());
  verifySetContents(set, iterable);
}
 
Example 32
Project: CustomWorldGen   File: GameRegistry.java   Source Code and License 5 votes vote down vote up
private static void computeSortedGeneratorList()
{
    ArrayList<IWorldGenerator> list = Lists.newArrayList(worldGenerators);
    Collections.sort(list, new Comparator<IWorldGenerator>()
    {
        @Override
        public int compare(IWorldGenerator o1, IWorldGenerator o2)
        {
            return Ints.compare(worldGeneratorIndex.get(o1), worldGeneratorIndex.get(o2));
        }
    });
    sortedGeneratorList = ImmutableList.copyOf(list);
}
 
Example 33
Project: Apriori   File: TieBreakerTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests the functionality of a multiple tie-breaking strategies for item sets.
 */
@Test
public final void testMultipleTieBreakingStrategiesForItemSets() {
    ItemSet itemSet1 = mock(ItemSet.class);
    ItemSet itemSet2 = mock(ItemSet.class);
    Comparator<ItemSet> comparator1 = (o1, o2) -> 0;
    Comparator<ItemSet> comparator2 = (o1, o2) -> -1;
    TieBreaker<ItemSet> tieBreaker = TieBreaker.forItemSets().custom(comparator1)
            .custom(comparator2);
    assertEquals(-1, tieBreaker.compare(itemSet1, itemSet2));
}
 
Example 34
Project: android-agenda-view   File: AgendaView.java   Source Code and License 5 votes vote down vote up
protected void drawShifts(Canvas canvas) {
    int px = 10;

    Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTextPaint.setTextSize(DEPARTMENT_FONT_SIZE);
    mTextPaint.setColor(Color.DKGRAY);

    Paint mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mLinePaint.setColor(Color.LTGRAY);

    ArrayList<List<IShift>> departments = new ArrayList<>();
    departments.addAll(ShiftHashData.values());

    Collections.sort(departments, new Comparator<List<IShift>>() {
        @Override
        public int compare(List<IShift> lhs, List<IShift> rhs) {
            return lhs.get(0).getSectionName().compareTo(rhs.get(0).getSectionName());
        }
    });

    for (List<IShift> department : departments) {
        List<ShiftLevel> added = new ArrayList<>();
        MaxHeight = 0;


        for (IShift shift : department) {
            // To check if the shift collides with other in the department
            drawRoundRect(canvas, shift, department, added);
        }

        IShift firstElement = department.get(0);

        // Write Dep. Name
        canvas.drawText(firstElement.getSectionName(), px, py + DEPARTMENT_FONT_SIZE + DEPARTMENT_VERTICAL_PADDING, mTextPaint);
        py = ROUND_RECT_PADDING + MaxHeight;
        canvas.drawLine(0, py, viewWidth, py, mLinePaint);
    }
}
 
Example 35
Project: hue   File: JoinDetector.java   Source Code and License 5 votes vote down vote up
private List<Entry<String, Integer>> sortMapByRatios(){
	Comparator<Entry<String, Integer>> byValue = (entry1, entry2) -> entry1.getValue().compareTo(
            entry2.getValue());

    List<Entry<String, Integer>> l = ratioMap
            .entrySet()
            .stream()
            .sorted(byValue.reversed())
            .collect(Collectors.toList());
    logger.debug("Sorted ratioMap: /n" + l);

    return l;
}
 
Example 36
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   Source Code and License 5 votes vote down vote up
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 37
Project: ProjectAres   File: Comparators.java   Source Code and License 5 votes vote down vote up
public static <T, U> Comparator<T> instancesFirst(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 38
Project: openjdk-jdk10   File: TestBCI.java   Source Code and License 5 votes vote down vote up
Optional<SortedSet<Integer>> findLineNumbers(int value) {
    return bciToLineNumbers.entrySet().stream()
            .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
            .filter(e -> e.getKey().intValue() <= value)
            .map(Map.Entry::getValue)
            .findFirst();
}
 
Example 39
Project: underlx   File: StationPickerView.java   Source Code and License 5 votes vote down vote up
@Override
public void sortStations(List<Station> stations) {
    final BellmanFordShortestPath<Stop, Connection> bfsp = new BellmanFordShortestPath<Stop, Connection>(network, startVertex);
    Collections.sort(stations, new Comparator<Station>() {
        @Override
        public int compare(Station station, Station t1) {
            return Double.compare(getStationWeight(station, bfsp), getStationWeight(t1, bfsp));
        }
    });

}
 
Example 40
Project: incubator-servicecomb-java-chassis   File: PerfStatMonitorMgr.java   Source Code and License 5 votes vote down vote up
public void registerPerfStat(PerfStat perfStat, int index) {
  String name = perfStat.getName();
  PerfStatMonitor monitor = monitorMap.get(name);
  if (monitor == null) {
    monitor = new PerfStatMonitor(name, index);
    monitorMap.put(name, monitor);

    monitorList.add(monitor);

    monitorList.sort(Comparator.comparingInt(PerfStatMonitor::getIndex));
  }

  monitor.addThreadStat(perfStat);
}
 
Example 41
Project: Pogamut3   File: GrahamScan2D.java   Source Code and License 5 votes vote down vote up
public Polygon2D convexHull(Collection<? extends Point2D> points) {
    int nbPoints = points.size();
    //TODO: manage small values of n
    
    // Find point with lowest y-coord
    Point2D lowestPoint = null;
    double lowestY = Double.MAX_VALUE;
    for(Point2D point : points){
        double y = point.getY();
        if(y<lowestY){
            lowestPoint = point;
            lowestY = y;
        }
    }
    
    // build the comparator, using the lowest point
    Comparator<Point2D> comparator = 
        new CompareByPseudoAngle(lowestPoint);
    
    // create a sorted set
    ArrayList<Point2D> sorted = new ArrayList<Point2D>(nbPoints);
    sorted.addAll(points);
    Collections.sort(sorted, comparator);
    
    // main loop
    // i-> current vertex of point cloud
    // m-> current hull vertex
    int m = 2;
    for(int i=3; i<nbPoints; i++){
        while(Point2D.ccw(sorted.get(m), sorted.get(m-1), 
                sorted.get(i))>=0)
            m--;
        m++;
        Collections.swap(sorted, m, i);
    }

    // Format result to return a polygon
    List<Point2D> hull = sorted.subList(0, Math.min(m+1, nbPoints));
    return new SimplePolygon2D(hull);
}
 
Example 42
Project: guava-mock   File: RegularImmutableSortedSet.java   Source Code and License 5 votes vote down vote up
@Override
ImmutableSortedSet<E> createDescendingSet() {
  Comparator<? super E> reversedOrder = Collections.reverseOrder(comparator);
  return isEmpty()
      ? emptySet(reversedOrder)
      : new RegularImmutableSortedSet<E>(elements.reverse(), reversedOrder);
}
 
Example 43
Project: googles-monorepo-demo   File: Helpers.java   Source Code and License 5 votes vote down vote up
public static <K, V> Comparator<Entry<K, V>> entryComparator(
    final Comparator<? super K> keyComparator) {
  return new Comparator<Entry<K, V>>() {
    @Override
    @SuppressWarnings("unchecked") // no less safe than putting it in the map!
    public int compare(Entry<K, V> a, Entry<K, V> b) {
      return (keyComparator == null)
          ? ((Comparable) a.getKey()).compareTo(b.getKey())
          : keyComparator.compare(a.getKey(), b.getKey());
    }
  };
}
 
Example 44
Project: powsybl-core   File: ShuntCompensatorsValidation.java   Source Code and License 5 votes vote down vote up
public static boolean checkShunts(Network network, ValidationConfig config, ValidationWriter shuntsWriter) {
    Objects.requireNonNull(network);
    Objects.requireNonNull(config);
    Objects.requireNonNull(shuntsWriter);
    LOGGER.info("Checking shunt compensators of network {}", network.getId());
    return network.getShuntStream()
                  .sorted(Comparator.comparing(ShuntCompensator::getId))
                  .map(shunt -> checkShunts(shunt, config, shuntsWriter))
                  .reduce(Boolean::logicalAnd)
                  .orElse(true);
}
 
Example 45
Project: ureport   File: DownDuplicate.java   Source Code and License 5 votes vote down vote up
public void complete(){
	if(minRowNumber<1){
		return;
	}
	Report report=context.getReport();
	Collections.sort(newRowList, new Comparator<Row>() {
		@Override
		public int compare(Row o1, Row o2) {
			return o1.getTempRowNumber()-o2.getTempRowNumber();
		}
	});
	report.insertRows(minRowNumber, newRowList);
}
 
Example 46
Project: Pogamut3   File: EngineSelectionComponent.java   Source Code and License 5 votes vote down vote up
/**
 * Get position into which to insert new child. Position is determined
 * as position of first child with greater or equal user object.
 *
 * @param newChildObject
 * @return
 */
@SuppressWarnings("unchecked")
public final int getChildPosition(CHILD_OBJECT newChildObject, Comparator<CHILD_OBJECT> comparator) {
    int childNodePosition = 0;
    Enumeration<DefaultMutableTreeNode> e = children();
    while (e.hasMoreElements()) {
        DefaultMutableTreeNode childNode = e.nextElement();
        CHILD_OBJECT childObject = (CHILD_OBJECT) childNode.getUserObject();
        if (comparator.compare(childObject, newChildObject) >= 0) {
            break;
        }
        childNodePosition++;
    }
    return childNodePosition;
}
 
Example 47
Project: openjdk-jdk10   File: LayoutFocusTraversalPolicy.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked") // Cast to (Comparator<? super Component>)
private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
{
    setComparator((Comparator<? super Component>)in.readObject());
    setImplicitDownCycleTraversal(in.readBoolean());
}
 
Example 48
Project: minsx-framework   File: SelectTest.java   Source Code and License 5 votes vote down vote up
@Test
public void selectMenu() {
    Map<Integer, List<Menu>> menuGroups = menuRepository.findAll().stream().sorted(Comparator.comparing(Menu::getSort)).collect(groupingBy(Menu::getParentMenuId));
    Node<Menu> rootNode = new Node<Menu>();
    completeChilds(rootNode, menuGroups);
    System.out.println(JSON.toJSONString(rootNode));
}
 
Example 49
Project: incubator-netbeans   File: PositionRegion.java   Source Code and License 5 votes vote down vote up
/**
 * Get comparator for position regions comparing start offsets
 * of the two given regions.
 *
 * @return non-null comparator comparing the start offsets of the two given
 *  regions.
 */
public static final Comparator<PositionRegion> getComparator() {
    if (comparator == null) {
        comparator = new Comparator<PositionRegion>() {
            public int compare(PositionRegion pr1, PositionRegion pr2) {
                return pr1.getStartOffset() - pr2.getStartOffset();
            }
        };
    }
    return comparator;
}
 
Example 50
Project: geomapapp   File: WWSceneGraph.java   Source Code and License 4 votes vote down vote up
private Collection<SceneItem> getAllItems(int subLayer,
		DrawContext dc, Angle startLon, Angle endLon, LatLon[] samples) {
	List<SceneItem> items = new LinkedList<SceneItem>();
	
	//Let's get the latitude range
	Angle[] latitudes = getLatitudeRange(samples);
	
	//We round for the polar cap for the latitudes closest to the pole
	int startLatIndex = getLatIndex(latitudes[0],latitudes[0].getDegrees()<0);
	int endLatIndex = getLatIndex(latitudes[1],latitudes[1].getDegrees()>0);
	
	int startLonIndex = getLonIndex(startLon);
	int endLonIndex = getLonIndex(endLon);
	
	//Check if we are looking at a pole, in which case we need the whole range
	if (startLatIndex == 0 || endLatIndex == NUM_LAT_DIVIDES-1) {
		startLonIndex = 0;
		endLonIndex = NUM_LON_DIVIDES-1;
	}

	LatLon center = dc.getViewportCenterPosition();
	final int midLonIndex = getLonIndex(center.getLongitude());
	final int midLatIndex = getLatIndex(center.getLatitude(), false);

	List<int[]> nodes = new LinkedList<int[]>();
	
	if (startLon.degrees > endLon.degrees) {
		for (int lat = startLatIndex; lat <= endLatIndex; lat++)
		{
			int midAIndex = getLonIndex(Angle.POS180);
			int midBIndex = getLonIndex(Angle.NEG180);
			for (int lon = startLonIndex; lon <= midAIndex; lon++)
				nodes.add(new int[] {lon,lat});
			for (int lon = midBIndex; lon <= endLonIndex; lon++)
				nodes.add(new int[] {lon,lat});
		}
	}
	else
		for (int lat = startLatIndex; lat <= endLatIndex; lat++)
			for (int lon = startLonIndex; lon <= endLonIndex; lon++)
				nodes.add(new int[] {lon,lat});
	
	Collections.sort(nodes, new Comparator<int[]>() {
		public int compare(int[] a, int[] b) {
			int dx = Math.abs(a[0] - midLonIndex);
			if (dx >= NUM_LON_DIVIDES / 2)
				dx = NUM_LON_DIVIDES - dx;
			
			double d1 = Math.pow(dx, 2) + 
						Math.pow(a[1] - midLatIndex, 2);
			
			dx = Math.abs(b[0] - midLonIndex);
			if (dx > NUM_LON_DIVIDES / 2)
				dx = NUM_LON_DIVIDES - dx;
			
			double d2 = Math.pow(dx, 2) + 
						Math.pow(b[1] - midLatIndex, 2);
			return (int) (10 * (d1 - d2));
		}
	});
	
	for (int[] node : nodes)
		if (root[node[0]][node[1]] != null) {
			retriveAllItems(subLayer, dc, root[node[0]][node[1]], items);
			if (items.size() > MAX_DRAWN_ITEMS)
				break;
		}
	return items;
}
 
Example 51
Project: Equella   File: UtilsScriptWrapper.java   Source Code and License 4 votes vote down vote up
@Override
public List<FacetCountResultScriptType> facetCount(String query, String[] collectionUuids, String where,
	String facetXpath)
{
	DefaultSearch search = createSearch(collectionUuids, where);
	search.setQuery(query);

	List<FacetCountResultScriptType> rv = Lists.newArrayList();

	if( facetXpath.startsWith("/xml") )
	{
		facetXpath = facetXpath.substring(facetXpath.indexOf('/', 1));
	}

	Multimap<String, Pair<String, Integer>> vcs = freetextIndex.facetCount(search,
		Collections.singletonList(facetXpath));
	for( Pair<String, Integer> valueCount : vcs.get(facetXpath) )
	{
		final String value = valueCount.getFirst();
		if( !Check.isEmpty(value) )
		{
			final int count = valueCount.getSecond();
			rv.add(new FacetCountResultScriptType()
			{
				@Override
				public String getTerm()
				{
					return value;
				}

				@Override
				public int getCount()
				{
					return count;
				}
			});
		}
	}

	Collections.sort(rv, new Comparator<FacetCountResultScriptType>()
	{
		@Override
		public int compare(FacetCountResultScriptType o1, FacetCountResultScriptType o2)
		{
			return o2.getCount() - o1.getCount();
		}
	});

	return rv;
}
 
Example 52
Project: Java-SE-9-Road-to-Concurrent-and-High-Performance-Programming   File: ArrayHeap.java   Source Code and License 4 votes vote down vote up
public ArrayHeap(int size, Comparator<E> comparator){
    store = (E[]) new Object[size];
    this.comparator = comparator;
}
 
Example 53
Project: marathonv5   File: CollatedTreeItem.java   Source Code and License 4 votes vote down vote up
public void setComparator(Comparator<T> c) {
    this.comparator = c;
    setCollation();
}
 
Example 54
Project: openmrs-contrib-addonindex   File: AddOnInfoAndVersions.java   Source Code and License 4 votes vote down vote up
public void addVersion(AddOnVersion version) {
	versions.add(version);
	versions.sort(Comparator.reverseOrder());
}
 
Example 55
Project: sats-core   File: RandomOrderXORQFactory.java   Source Code and License 4 votes vote down vote up
@Override
protected Comparator<SRVMBand> getDefComparator() {
    return comparator;
}
 
Example 56
Project: guava-mock   File: ImmutableSortedMap.java   Source Code and License 4 votes vote down vote up
private static <K, V> ImmutableSortedMap<K, V> newView(
    SortedMap<K, V> delegate, Comparator<? super K> comparator) {
  return new ImmutableSortedMap<K, V>(delegate, comparator);
}
 
Example 57
Project: firebase-admin-java   File: ArraySortedMap.java   Source Code and License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private ArraySortedMap(Comparator<K> comparator, K[] keys, V[] values) {
  this.keys = keys;
  this.values = values;
  this.comparator = comparator;
}
 
Example 58
Project: sstore-soft   File: AbstractMapBasedMultimap.java   Source Code and License 4 votes vote down vote up
@Override
public Comparator<? super K> comparator() {
  return sortedMap().comparator();
}
 
Example 59
Project: parabuild-ci   File: SessionImpl.java   Source Code and License 4 votes vote down vote up
private void endLoadingCollections(CollectionPersister persister, List resultSetCollections)
throws HibernateException {

	final int count = resultSetCollections==null ? 0 : resultSetCollections.size();

	if ( log.isDebugEnabled() ) log.debug( count + " collections were found in result set" );

	//now finish them
	for ( int i=0; i<count; i++ ) {
		LoadingCollectionEntry lce = (LoadingCollectionEntry) resultSetCollections.get(i);
		boolean noQueuedAdds = lce.collection.endRead(); //warning: can cause a recursive query! (proxy initialization)
		CollectionEntry ce = getCollectionEntry(lce.collection);
		if (ce==null) {
			ce = addInitializedCollection(lce.collection, persister, lce.id);
		}
		else {
			ce.postInitialize(lce.collection);
		}
		if ( noQueuedAdds && persister.hasCache() && !ce.doremove ) {
			if ( log.isDebugEnabled() ) log.debug( "Caching collection: " + MessageHelper.infoString(persister, lce.id) );
			ClassPersister ownerPersister = factory.getPersister( persister.getOwnerClass() );
			Object version;
			Comparator versionComparator;
			if ( ownerPersister.isVersioned() ) {
				version = getEntry( getCollectionOwner(ce) ).version;
				versionComparator = ownerPersister.getVersionType().getComparator();
			}
			else {
				version = null;
				versionComparator = null;
			}
			persister.getCache().put( 
					lce.id, lce.collection.disassemble(persister), getTimestamp(), version, versionComparator
			);
		}

		if ( log.isDebugEnabled() ) log.debug( "collection fully initialized: " + MessageHelper.infoString(persister, lce.id) );
	}

	if ( log.isDebugEnabled() ) log.debug( count + " collections initialized" );
}
 
Example 60
Project: NanoUI   File: TimSort.java   Source Code and License 4 votes vote down vote up
/** Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element
 * equal to key, returns the index of the leftmost equal element.
 * 
 * @param key the key whose insertion point to search for
 * @param a the array in which to search
 * @param base the index of the first element in the range
 * @param len the length of the range; must be > 0
 * @param hint the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method
 *           will run.
 * @param c the comparator used to order the range, and to search
 * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k], pretending that a[b - 1] is minus infinity and a[b
 *         + n] is infinity. In other words, key belongs at index b + k; or in other words, the first k elements of a should
 *         precede key, and the last n - k should follow it. */
private static <T> int gallopLeft (T key, T[] a, int base, int len, int hint, Comparator<? super T> c) {
	if (DEBUG) assert len > 0 && hint >= 0 && hint < len;
	int lastOfs = 0;
	int ofs = 1;
	if (c.compare(key, a[base + hint]) > 0) {
		// Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
		int maxOfs = len - hint;
		while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
			lastOfs = ofs;
			ofs = (ofs << 1) + 1;
			if (ofs <= 0) // int overflow
				ofs = maxOfs;
		}
		if (ofs > maxOfs) ofs = maxOfs;

		// Make offsets relative to base
		lastOfs += hint;
		ofs += hint;
	} else { // key <= a[base + hint]
		// Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
		final int maxOfs = hint + 1;
		while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
			lastOfs = ofs;
			ofs = (ofs << 1) + 1;
			if (ofs <= 0) // int overflow
				ofs = maxOfs;
		}
		if (ofs > maxOfs) ofs = maxOfs;

		// Make offsets relative to base
		int tmp = lastOfs;
		lastOfs = hint - ofs;
		ofs = hint - tmp;
	}
	if (DEBUG) assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;

	/*
	 * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere to the right of lastOfs but no farther right than ofs.
	 * Do a binary search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
	 */
	lastOfs++;
	while (lastOfs < ofs) {
		int m = lastOfs + ((ofs - lastOfs) >>> 1);

		if (c.compare(key, a[base + m]) > 0)
			lastOfs = m + 1; // a[base + m] < key
		else
			ofs = m; // key <= a[base + m]
	}
	if (DEBUG) assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
	return ofs;
}