下面列出了怎么用com.google.common.collect.ComparisonChain的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* This method sorts all contexts alphabetically so that the file always gets generated in the same order.
*
* @param model
* context model
*/
private void sortAllContexts(final CtxHelpModel model) {
Ordering<CtxHelpContext> ordering = Ordering.from((a, b) -> ComparisonChain.start().compare(a.getId(), b.getId()).result());
List<CtxHelpContext> allContexts = Lists.newArrayList(Iterables.filter(model.getCtxHelpRoot().getChildren(), CtxHelpContext.class));
List<CtxHelpContext> expectedContexts = ordering.sortedCopy(allContexts);
CtxHelpRoot root = model.getCtxHelpRoot();
if (!expectedContexts.equals(allContexts)) {
for (int i = 0; i < expectedContexts.size(); i++) {
CtxHelpContext expected = expectedContexts.get(i);
CtxHelpContext actual = allContexts.get(i);
if (!actual.getId().equals(expected.getId())) {
root.swap(actual, expected);
allContexts.set(allContexts.indexOf(expected), actual);
allContexts.set(i, expected);
}
}
}
}
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
Map<String, Long> map = _eventStore.snapshotClaimCounts();
if (map.isEmpty()) {
output.println("no claims");
return;
}
// Sort the entries in the map from biggest to smallest.
List<Map.Entry<String,Long>> entries = Lists.newArrayList(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Long>>() {
@Override
public int compare(Map.Entry<String, Long> e1, Map.Entry<String, Long> e2) {
return ComparisonChain.start()
.compare(e2.getValue(), e1.getValue()) // Sort counts descending
.compare(e1.getKey(), e2.getKey()) // Sort channel names ascending
.result();
}
});
// Print a formatted table with two columns.
for (Map.Entry<String, Long> entry : entries) {
output.println(Strings.padStart(entry.getValue().toString(), 9, ' ') + " " + entry.getKey());
}
}
@Override
public int compareTo(BlobValue o) {
if (bytes.isPresent() && o.bytes.isPresent()) {
return ComparisonChain.start()
.compare(bytes.get(), o.bytes.get())
.compare(this.name, o.name)
.result();
} else {
// either bytes or o.bytes is empty
if (bytes.isPresent()) {
return 1;
} else if (o.bytes.isPresent()) {
return -1;
} else {
return 0;
}
}
}
public Comparator<SingularityTaskIdHistory> getComparator() {
final OrderDirection localOrderDirection = orderDirection.orElse(OrderDirection.DESC);
return new Comparator<SingularityTaskIdHistory>() {
@Override
public int compare(SingularityTaskIdHistory o1, SingularityTaskIdHistory o2) {
ComparisonChain chain = ComparisonChain.start();
if (localOrderDirection == OrderDirection.ASC) {
chain = chain.compare(o1.getUpdatedAt(), o2.getUpdatedAt());
} else {
chain = chain.compare(o2.getUpdatedAt(), o1.getUpdatedAt());
}
return chain
.compare(o1.getTaskId().getRequestId(), o2.getTaskId().getRequestId())
.result();
}
};
}
/** @deprecated since 0.7.0; kept for persisted state backwards compatibility */
@Deprecated
@SuppressWarnings("unused")
private static Ordering<Image> orderingWithDefaultsDeprecated(final Ordering<Image> primaryOrdering) {
return new Ordering<Image>() {
@Override
public int compare(Image left, Image right) {
return ComparisonChain.start()
.compare(left, right, primaryOrdering)
// fall back to default strategy otherwise, except preferring *non*-null values
// TODO suggest to use NaturalOrderComparator (so 10>9) then order by:
// 1) `name.replaceAll("([^0-9]+)", " ")`
// 2) shortest non-empty name
// 3) version (NaturalOrderComparator, prefer last)
// 4) name (NaturalOrderComparator, prefer last)
// 5) other fields (NaturalOrderComparator, prefer last)
.compare(left.getName(), right.getName(), Ordering.<String> natural().nullsFirst())
.compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsFirst())
.compare(left.getDescription(), right.getDescription(), Ordering.<String> natural().nullsFirst())
.compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(), Ordering.<String> natural().nullsFirst())
.compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(), Ordering.<String> natural().nullsFirst())
.compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(), Ordering.<String> natural().nullsFirst())
.compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch(), Ordering.<String> natural().nullsFirst()).result();
}
};
}
public DatatypeLong(final Comparator<Long> comparator) {
this.specificType = type.LONG;
if (comparator == null) {
this.indexedComparator = new Comparator<RowIndexedLongValue>() {
@Override
public int compare(final RowIndexedLongValue o1, final RowIndexedLongValue o2) {
return ComparisonChain.start()
.compare(o1.value, o2.value, Ordering.natural().nullsFirst()).result();
}
};
} else {
this.indexedComparator = new Comparator<RowIndexedLongValue>() {
@Override
public int compare(final RowIndexedLongValue o1, final RowIndexedLongValue o2) {
return ComparisonChain.start()
.compare(o1.value, o2.value, Ordering.from(comparator).nullsFirst()).result();
}
};
}
}
/**
* Returns whether this version is at least as recent as the given version.
*
* @param version
* The version to compare against.
*
* @return
* true if the versions are associated with the same database server
* type (MariaDB vs. MySQL) and this version is at least as recent as
* the given version, false otherwise.
*/
public boolean isAtLeast(MySQLVersion version) {
// If the databases use different version numbering schemes, the
// version numbers are not comparable
if (isMariaDB != version.isMariaDB)
return false;
// Compare major, minor, and patch number in order of precedence
return ComparisonChain.start()
.compare(major, version.major)
.compare(minor, version.minor)
.compare(patch, version.patch)
.result() >= 0;
}
@Override
public int compare(final Answerable left, final Answerable right) {
final Optional<Response> earliestLeftResponse = earliestResponse(left);
final Optional<Response> earliestRightResponse = earliestResponse(right);
if (earliestLeftResponse.isPresent()) {
if (earliestRightResponse.isPresent()) {
return ComparisonChain.start()
.compare(earliestLeftResponse.get(), earliestRightResponse.get(),
Response.ByJustificationLocation)
.compare(left, right)
.result();
} else {
return -1;
}
} else if (earliestRightResponse.isPresent()) {
return 1;
} else {
return left.compareTo(right);
}
}
public int compareTo(@Nonnull AegisthusKey other, Comparator<ByteBuffer> nameComparator) {
// This is a workaround for comparators not handling nulls properly
// The case where name or timestamp is null should only happen when there has been a delete
int result = this.key.compareTo(other.key);
if (result != 0) {
return result;
}
result = this.sourcePath.compareTo(other.sourcePath);
if (result != 0) {
return result;
}
if (this.name == null || this.timestamp == null) {
return -1;
} else if (other.name == null || other.timestamp == null) {
return 1;
}
return ComparisonChain.start()
.compare(this.name, other.name, nameComparator)
.compare(this.timestamp, other.timestamp)
.result();
}
private Object typesDescriptors() {
List<Map<String,Comparable<?>>> result = new ArrayList<>(tClasses.size());
for (TClass tClass : tClasses) {
Map<String,Comparable<?>> map = new LinkedHashMap<>();
buildTName("bundle", "name", tClass, map);
map.put("category", tClass.name().categoryName());
map.put("internalVersion", tClass.internalRepresentationVersion());
map.put("serializationVersion", tClass.serializationVersion());
map.put("fixedSize", tClass.hasFixedSerializationSize() ? tClass.fixedSerializationSize() : null);
result.add(map);
}
Collections.sort(result, new Comparator<Map<String, Comparable<?>>>() {
@Override
public int compare(Map<String, Comparable<?>> o1, Map<String, Comparable<?>> o2) {
return ComparisonChain.start()
.compare(o1.get("bundle"), o2.get("bundle"))
.compare(o1.get("category"), o2.get("category"))
.compare(o1.get("name"), o2.get("name"))
.result();
}
});
return result;
}
@Override
public int compareTo(CxxLinkGroupMappingTarget that) {
if (this == that) {
return 0;
}
int labelComparison = compareLabelPattern(that);
if (labelComparison != 0) {
return labelComparison;
}
return ComparisonChain.start()
.compare(this.getBuildTarget(), that.getBuildTarget())
.compare(this.getTraversal(), that.getTraversal())
.result();
}
List<TabListEntry> getVisibleEntries() {
if (visibleEntries == null) {
List<TabListEntry> entries = new ArrayList<>(this.entries.values());
entries.sort(new Comparator<TabListEntry>() {
@Override
public int compare(TabListEntry o1, TabListEntry o2) {
return ComparisonChain.start().compareTrueFirst(o1.getGamemode() != 3, o2.getGamemode() != 3)
.compare(MoreObjects.firstNonNull(playerToTeamMap.get(o1.getUsername()), ""), MoreObjects.firstNonNull(playerToTeamMap.get(o2.getUsername()), ""))
.compare(o1.getUsername(), o2.getUsername()).result();
}
});
if (entries.size() > 80) {
entries = entries.subList(0, 80);
}
visibleEntries = Collections.unmodifiableList(entries);
}
return visibleEntries;
}
@Override
// TODO: is this efficient enough? It seems slow
public int compareTo(MultipleSpatioTemporalWritable arg0) {
spatialComp = arg0.getSpatial();
temporalComp = arg0.getTemporal();
ch = ComparisonChain.start();
// assuming they have the same size
for (int i = 0; i < this.spatial.length; i++)
ch = ch.compare(this.spatial[i], spatialComp[i]);
for (int i = 0; i < this.temporal.length; i++)
ch = ch.compare(this.temporal[i], temporalComp[i]);
return ch.result();
}
@Override
public int compareTo(FunctionIdent o) {
return ComparisonChain.start()
.compare(fqnName, o.fqnName)
.compare(argumentTypes, o.argumentTypes, Ordering.<DataType<?>>natural().lexicographical())
.result();
}
@Override
public int compare(final Response left, final Response right) {
return ComparisonChain.start()
.compare(left.docID().toString(), right.docID().toString())
.compare(
Ordering.natural().sortedCopy(left.predicateJustifications()),
Ordering.natural().sortedCopy(right.predicateJustifications()),
Ordering.<CharOffsetSpan>natural().lexicographical())
.compare(left.baseFiller(), right.baseFiller())
.compare(left.canonicalArgument().charOffsetSpan(),
right.canonicalArgument().charOffsetSpan())
.compare(left.realis(), right.realis())
.result();
}
@Override
public int compareTo(FunctionName o) {
return ComparisonChain.start()
.compare(schema, o.schema)
.compare(name, o.name)
.result();
}
@Override
public int compare(SemanticHighlightingInformation left, SemanticHighlightingInformation right) {
//@formatter:off
return ComparisonChain.start()
.compare(left.getLine(), right.getLine())
.result();
//@formatter:on
}
@Override
protected void onKeyType(char character, int key) {
ITextfield textfield = getTextfieldById(1);
if (textfield.callIsFocused() && !The5zigMod.getVars().isPlayerNull() && key == Keyboard.KEY_TAB) {
if (tabWord == null) {
tabWord = textfield.callGetText().toLowerCase();
}
List<NetworkPlayerInfo> tabPlayers = The5zigMod.getVars().getServerPlayers();
Collections.sort(tabPlayers, new Comparator<NetworkPlayerInfo>() {
@Override
public int compare(NetworkPlayerInfo t0, NetworkPlayerInfo t1) {
return ComparisonChain.start().compare(t0.getGameProfile().getName(), t1.getGameProfile().getName()).result();
}
});
for (Iterator<NetworkPlayerInfo> it = tabPlayers.iterator(); it.hasNext(); ) {
NetworkPlayerInfo next = it.next();
if (next.getGameProfile().getName() == null || !next.getGameProfile().getName().toLowerCase().startsWith(tabWord)) {
it.remove();
}
}
if (!tabPlayers.isEmpty()) {
tabIndex = tabIndex % tabPlayers.size();
NetworkPlayerInfo playerInfo = tabPlayers.get(tabIndex);
textfield.callSetText(playerInfo.getGameProfile().getName());
tabIndex = (tabIndex + 1) % tabPlayers.size();
}
} else {
tabIndex = 0;
tabWord = null;
}
}
@Override
public int compareTo(ChangedRow that)
{
return ComparisonChain.start()
.compare(this.row, that.row, rowComparator(precision))
.compareFalseFirst(this.changed == Changed.ADDED, that.changed == Changed.ADDED)
.result();
}
@Override
public int compare(AclEntry entry1, AclEntry entry2) {
return ComparisonChain.start()
.compare(entry1.getScope(), entry2.getScope(),
Ordering.explicit(ACCESS, DEFAULT))
.compare(entry1.getType(), entry2.getType(),
Ordering.explicit(USER, GROUP, MASK, OTHER))
.compare(entry1.getName(), entry2.getName(),
Ordering.natural().nullsFirst())
.result();
}
@Override
public int compareTo(FifoRunnableTask<T> other)
{
return ComparisonChain.start()
.compare(this.task, other.task, taskComparator)
.compare(this.sequenceNumber, other.sequenceNumber)
.result();
}
@Test
public void testForVcf() throws Exception {
final Segment entireThing = new Segment(1, 9942);
final ImmutableList<Segment> expectedSubThings = ImmutableList.of(
new Segment(1, 1000),
new Segment(1001, 2000),
new Segment(2001, 3000),
new Segment(3001, 4000),
new Segment(4001, 5000),
new Segment(5001, 6000),
new Segment(6001, 7000),
new Segment(7001, 8000),
new Segment(8001, 9000),
new Segment(9001, 9942)
);
final VcfFileSegmentGenerator.WidthLimitingDecorator strategy = VcfFileSegmentGenerator.WidthLimitingDecorator.wrapping(new VcfFileSegmentGenerator() {
@Override
public Iterable<VcfFileSegment> forVcf(final File vcf) {
return Collections.singleton((VcfFileSegment) entireThing);
}
}, 1000);
final List<VcfFileSegment> observed = new ArrayList<VcfFileSegment>();
Iterators.addAll(observed, strategy.forVcf(new File("B")).iterator());
final Iterator<VcfFileSegment> observedIterator = observed.iterator();
for (final VcfFileSegment e : expectedSubThings) {
Assert.assertTrue(observedIterator.hasNext());
final VcfFileSegment o = observedIterator.next();
Assert.assertEquals(ComparisonChain.start()
.compare(o.contig(), e.contig())
.compare(o.start(), e.start())
.compare(o.stop(), e.stop())
.compare(o.vcf(), e.vcf())
.result(), 0, String.format(String.format("observed=%[email protected]%s:%s-%s expected=%s", o.vcf(), o.contig(), o.start(),
o.stop(), e.toString())));
}
}
@Override
public int compareTo(final Suggestion other) {
return ComparisonChain.start()
.compare(confidenceGap, other.confidenceGap)
.compare(identifierName, other.identifierName)
.compare(scope, other.scope).result();
}
private static Comparator<SearchResult> sorted(final List<SortField> fields) {
return (o1, o2) -> {
ComparisonChain chain = ComparisonChain.start();
for(SortField field : fields) {
Comparable f1 = (Comparable) o1.getSource().get(field.getField());
Comparable f2 = (Comparable) o2.getSource().get(field.getField());
chain = chain.compare(f1, f2, new ComparableComparator(field.getSortOrder()));
}
return chain.result();
};
}
@Override
public int compareTo(Aggregation arg0) {
Min agg = (Min) arg0;
return ComparisonChain.start().
compare(min, agg.getMin()).
compare(count, agg.getCount()).
result();
}
/**
* Always sort notifications in descending order (largest IDs first)
*
* @param that Notification to compare to
* @return 1 if this greater than that, 0 if this equal to that, or -1 if this less than that
*/
@Override
public int compareTo(final Notification that) {
return ComparisonChain.start()
.compare(this.getId(""), that.getId(""), Comparator.reverseOrder())
.result();
}
@Override
public int compareTo(Key o) {
return ComparisonChain.start()
.compare(this.namespace, o.namespace)
.compare(this.table, o.table)
.compare(this.partitionKey, o.partitionKey)
.compare(
this.clusteringKey.orElse(null),
o.clusteringKey.orElse(null),
Ordering.natural().nullsFirst())
.result();
}
@Override
public int compareTo(QualifiedName o) {
return ComparisonChain.start()
.compare(packageName, o.packageName)
.compare(simpleNames, o.simpleNames, Ordering.natural().lexicographical())
.result();
}
@Override
public int compareTo(SingularityRequestHistory o) {
return ComparisonChain
.start()
.compare(o.getCreatedAt(), createdAt)
.compare(request.getId(), o.getRequest().getId())
.result();
}
@Override
public int compareKey(PointSensitivity other) {
if (other instanceof DummyPointSensitivity) {
DummyPointSensitivity otherZero = (DummyPointSensitivity) other;
return ComparisonChain.start()
.compare(curveCurrency, otherZero.curveCurrency)
.compare(currency, otherZero.currency)
.compare(date, otherZero.date)
.result();
}
return getClass().getSimpleName().compareTo(other.getClass().getSimpleName());
}