本文整理汇总了Java中java.util.Comparator类的典型用法代码示例。如果您正苦于以下问题:Java Comparator类的具体用法?Java Comparator怎么用?Java Comparator使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Comparator类属于java.util包,在下文中一共展示了Comparator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: calculateChecksum
import java.util.Comparator; //导入依赖的package包/类
/**
* 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() + "'");
}
}
示例2: createObjectArrayComparator
import java.util.Comparator; //导入依赖的package包/类
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;
}
};
}
示例3: copyOf
import java.util.Comparator; //导入依赖的package包/类
/**
* 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);
}
示例4: testLexicographicalComparatorLongInputs
import java.util.Comparator; //导入依赖的package包/类
@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);
}
}
}
示例5: testCustomComparator
import java.util.Comparator; //导入依赖的package包/类
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());
}
示例6: fireRegistryEvents
import java.util.Comparator; //导入依赖的package包/类
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
}
示例7: write
import java.util.Comparator; //导入依赖的package包/类
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);
}
示例8: ensureFailoverIsInitialized
import java.util.Comparator; //导入依赖的package包/类
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;
}
}
示例9: toNonNullOpenValue
import java.util.Comparator; //导入依赖的package包/类
@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;
}
示例10: copyOfInternal
import java.util.Comparator; //导入依赖的package包/类
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());
}
示例11: updateFavorites
import java.util.Comparator; //导入依赖的package包/类
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));
}
示例12: SortState
import java.util.Comparator; //导入依赖的package包/类
/**
* 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];
}
示例13: getDefendingUnit
import java.util.Comparator; //导入依赖的package包/类
/**
* {@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);
}
示例14: getMostRecent
import java.util.Comparator; //导入依赖的package包/类
/**
*
* @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);
}
示例15: containsAll
import java.util.Comparator; //导入依赖的package包/类
/**
* 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;
}