下面列出了怎么用com.google.common.collect.Ordering的API类实例代码及写法,或者点击链接到github查看源代码。
@VisibleForTesting
final ImmutableList<MetricPoint<Long>> getTimestampedValues(Instant endTimestamp) {
ImmutableList.Builder<MetricPoint<Long>> timestampedValues = new ImmutableList.Builder<>();
for (Entry<ImmutableList<String>, Long> entry : values.asMap().entrySet()) {
ImmutableList<String> labelValues = entry.getKey();
valueLocks.get(labelValues).lock();
Instant startTimestamp;
try {
startTimestamp = valueStartTimestamps.get(labelValues);
} finally {
valueLocks.get(labelValues).unlock();
}
// There is an opportunity for endTimestamp to be less than startTimestamp if
// one of the modification methods is called on a value before the lock for that value is
// acquired but after getTimestampedValues has been invoked. Just set endTimestamp equal to
// startTimestamp if that happens.
endTimestamp = Ordering.natural().max(startTimestamp, endTimestamp);
timestampedValues.add(
MetricPoint.create(this, labelValues, startTimestamp, endTimestamp, entry.getValue()));
}
return timestampedValues.build();
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
protected Comparator getItemsComparator() {
return Ordering.natural().nullsLast().from(new Comparator() {
@Override
public int compare(final Object o1, final Object o2) {
if (o1 instanceof IEObjectDescription && o2 instanceof IEObjectDescription) {
final IEObjectDescription d1 = (IEObjectDescription) o1;
final IEObjectDescription d2 = (IEObjectDescription) o2;
final QualifiedName fqn1 = d1.getQualifiedName();
final QualifiedName fqn2 = d2.getQualifiedName();
if (null != fqn1 && null != fqn2) {
return nullToEmpty(fqn1.getLastSegment()).compareToIgnoreCase(
nullToEmpty(fqn2.getLastSegment()));
}
}
return Objects.hashCode(o1) - Objects.hashCode(o2);
}
});
}
public static void validateExecution(
@Nullable Module module,
@Nullable AndroidFacet facet,
@Nullable ProjectViewSet projectViewSet)
throws ExecutionException {
List<ValidationError> errors = Lists.newArrayList();
errors.addAll(validateModule(module));
if (module != null) {
errors.addAll(validateFacet(facet, module));
}
if (projectViewSet == null) {
errors.add(ValidationError.fatal("Could not load project view. Please resync project"));
}
if (errors.isEmpty()) {
return;
}
ValidationError topError = Ordering.natural().max(errors);
if (topError.isFatal()) {
throw new ExecutionException(topError.getMessage());
}
}
/** Converts the object to string using Starlark syntax. */
@Override
public void repr(Printer printer) {
boolean first = true;
printer.append("struct(");
for (String fieldName : Ordering.natural().sortedCopy(getFieldNames())) {
if (!first) {
printer.append(", ");
}
first = false;
printer.append(fieldName);
printer.append(" = ");
printer.repr(getValueOrNull(fieldName));
}
printer.append(")");
}
@Test
public void testOneMoreByteVLongDimEncPreserveOrder() {
// TODO: better test
OneMoreByteVLongDimEnc enc = new OneMoreByteVLongDimEnc(2);
List<ByteArray> encodedValues = Lists.newArrayList();
encodedValues.add(encode(enc, -32768L));
encodedValues.add(encode(enc, -10000L));
encodedValues.add(encode(enc, -100L));
encodedValues.add(encode(enc, 0L));
encodedValues.add(encode(enc, 100L));
encodedValues.add(encode(enc, 10000L));
encodedValues.add(encode(enc, 32767L));
encodedValues.add(encode(enc, null));
assertTrue(Ordering.from(new DefaultGTComparator()).isOrdered(encodedValues));
}
/**
* Converts the provided value map into the equivalent transition map, using transition objects
* of the given TimedTransition subclass. The value map must be sorted according to the natural
* ordering of its DateTime keys, and keys cannot be earlier than START_OF_TIME.
*/
// NB: The Class<T> parameter could be eliminated by getting the class via reflection, but then
// the callsite cannot infer T, so unless you explicitly call this as .<V, T>fromValueMap() it
// will default to using just TimedTransition<V>, which fails at runtime.
private static <V, T extends TimedTransition<V>> NavigableMap<DateTime, T> makeTransitionMap(
ImmutableSortedMap<DateTime, V> valueMap,
final Class<T> timedTransitionSubclass) {
checkArgument(
Ordering.natural().equals(valueMap.comparator()),
"Timed transition value map must have transition time keys in chronological order");
return Maps.transformEntries(
valueMap,
(DateTime transitionTime, V value) -> {
checkArgument(
!transitionTime.isBefore(START_OF_TIME),
"Timed transition times cannot be earlier than START_OF_TIME / Unix Epoch");
T subclass = TypeUtils.instantiate(timedTransitionSubclass);
((TimedTransition<V>) subclass).transitionTime = transitionTime;
subclass.setValue(value);
return subclass;
});
}
@Test
public void testFeeExtension_premium_eap_v06_withRenewalOnRestore() throws Exception {
createTld("example");
setEppInput("domain_check_fee_premium_v06.xml");
clock.setTo(DateTime.parse("2010-01-01T10:00:00Z"));
persistPendingDeleteDomain("rich.example");
persistResource(
Registry.get("example")
.asBuilder()
.setEapFeeSchedule(
new ImmutableSortedMap.Builder<DateTime, Money>(Ordering.natural())
.put(START_OF_TIME, Money.of(USD, 0))
.put(clock.nowUtc().minusDays(1), Money.of(USD, 100))
.put(clock.nowUtc().plusDays(1), Money.of(USD, 50))
.put(clock.nowUtc().plusDays(2), Money.of(USD, 0))
.build())
.build());
runFlowAssertResponse(loadFile("domain_check_fee_premium_eap_response_v06_with_renewal.xml"));
}
/**
* Parses a set of maven repository directory trees looking for and parsing .pom files.
*/
static SdkMavenRepository create(Iterable<Path> mavenRepositories) throws IOException {
Collection<Path> pomPaths = new ArrayList<>();
for (Path mavenRepository : mavenRepositories) {
pomPaths.addAll(
FileSystemUtils.traverseTree(mavenRepository, path -> path.toString().endsWith(".pom")));
}
ImmutableSortedSet.Builder<Pom> poms =
new ImmutableSortedSet.Builder<>(Ordering.usingToString());
for (Path pomPath : pomPaths) {
try {
Pom pom = Pom.parse(pomPath);
if (pom != null) {
poms.add(pom);
}
} catch (ParserConfigurationException | SAXException e) {
throw new IOException(e);
}
}
return new SdkMavenRepository(poms.build());
}
@Override
public void removeInactiveAgents(int durationDays) {
if (durationDays < MIN_DURATION_DAYS_FOR_INACTIVITY) {
throw new IllegalArgumentException("duration may not be less than " + MIN_DURATION_DAYS_FOR_INACTIVITY + " days");
}
Map<String, List<String>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
List<Application> applications = this.applicationIndexDao.selectAllApplicationNames();
Set<String> applicationNames = new TreeSet<>(Ordering.usingToString());
// remove duplicates (same application name but different service type)
for (Application application : applications) {
applicationNames.add(application.getName());
}
for (String applicationName : applicationNames) {
List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
Collections.sort(agentIds);
List<String> inactiveAgentIds = filterInactiveAgents(agentIds, durationDays);
if (!CollectionUtils.isEmpty(inactiveAgentIds)) {
inactiveAgentMap.put(applicationName, inactiveAgentIds);
}
}
// map may become big, but realistically won't cause OOM
// if it becomes an issue, consider deleting inside the loop above
logger.info("deleting {}", inactiveAgentMap);
this.applicationIndexDao.deleteAgentIds(inactiveAgentMap);
}
/**
* Computes ordering for the search results. If none are specified - then
* returns the default ordering. The resulting ordering is always compounded
* with ordering by wave id for stability.
*/
public static Ordering<WaveViewData> computeSorter(
Map<TokenQueryType, Set<String>> queryParams) {
Ordering<WaveViewData> ordering = null;
Set<String> orderBySet = queryParams.get(TokenQueryType.ORDERBY);
if (orderBySet != null) {
for (String orderBy : orderBySet) {
QueryHelper.OrderByValueType orderingType =
QueryHelper.OrderByValueType.fromToken(orderBy);
if (ordering == null) {
// Primary ordering.
ordering = orderingType.getOrdering();
} else {
// All other ordering are compounded to the primary one.
ordering = ordering.compound(orderingType.getOrdering());
}
}
} else {
ordering = QueryHelper.DEFAULT_ORDERING;
}
// For stability order also by wave id.
ordering = ordering.compound(QueryHelper.ID_COMPARATOR);
return ordering;
}
public List<TPatternMatch> shuffle(int nMatchesToModify) throws Exception {
final Ordering<? super TPatternMatch> ordering = Ordering.from(comparator);
// some tools, e.g. Neo4j require to be in a transaction to get properties
// (used to get the ID properties for ordering)
driver.beginTransaction();
sortedMatches = ordering.sortedCopy(matches);
driver.finishTransaction();
final int size = sortedMatches.size();
if (size < nMatchesToModify) {
nMatchesToModify = size;
}
Collections.shuffle(sortedMatches, random);
candidates = new ArrayList<>(nMatchesToModify);
for (int i = 0; i < nMatchesToModify; i++) {
final TPatternMatch candidate = sortedMatches.get(i);
candidates.add(candidate);
}
return candidates;
}
/**
* Incomplete, assigned explicitly to me, AND ALSO any tasks not assigned to anyone but for which
* I have the (party) roles to perform them (so should be part of "my tasks") before {@param createdOn}
* @param createdOn
* @return
*/
@Programmatic
public List<Task> findIncompleteForMeAndCreatedOnBefore(final LocalDateTime createdOn){
final Person meAsPerson = meAsPerson();
if(meAsPerson == null) {
return Lists.newArrayList();
}
final List<Task> tasks = findIncompleteForAndCreatedOnBefore(meAsPerson, createdOn);
final List<Task> myRolesTasksUnassigned = findIncompleteForMyRolesAndUnassignedAndCreatedOnBefore(createdOn);
tasks.addAll(myRolesTasksUnassigned);
Comparator<Task> comparator = Comparator.comparing(Task::getPriority, Ordering.natural().nullsLast())
.thenComparing(Task::getCreatedOn, Ordering.natural().nullsLast().reverse());
tasks.sort(comparator);
return tasks;
}
private List<double[]> getNeighbors(int curIndex, IntList svdIndices,
SVDFeature svdFeature,
List<String> features) {
List<double[]> raw = new ArrayList<>(svdIndices.size());
for (int target : svdIndices) {
if (target != curIndex && (numMatch == 0 || matchPrefixFeatures(curIndex, target, features))) {
double[] pair = new double[2];
pair[0] = target;
pair[1] = svdFeature.getVectorVarByNameIndex(SVDFeatureKey.FACTORS.get(), target)
.cosine(svdFeature.getVectorVarByNameIndex(SVDFeatureKey.FACTORS.get(), curIndex));
raw.add(pair);
}
}
Ordering<double[]> pairDoubleOrdering = SortingUtilities.pairDoubleSecondOrdering();
List<double[]> neighbors;
if (reverse) {
neighbors = pairDoubleOrdering.leastOf(raw, numNeighbors);
} else {
neighbors = pairDoubleOrdering.greatestOf(raw, numNeighbors);
}
return neighbors;
}
private static List<Integer> secondary(Issue issue) {
List<Integer> result = new ArrayList<>();
if (issue instanceof PreciseIssue) {
result.addAll(((PreciseIssue) issue).secondaryLocations()
.stream()
.map(IssueLocation::startLine)
.collect(Collectors.toList()));
} else if (issue instanceof FileIssue) {
result.addAll(((FileIssue) issue).secondaryLocations()
.stream()
.map(IssueLocation::startLine)
.collect(Collectors.toList()));
}
return Ordering.natural().sortedCopy(result);
}
public DatatypeDate(final Comparator<Date> comparator, final String dateFormat) {
this.specificType = type.DATE;
this.setDateFormat(dateFormat);
if (comparator == null) {
this.indexedComparator = new Comparator<RowIndexedDateValue>() {
@Override
public int compare(final RowIndexedDateValue o1, final RowIndexedDateValue o2) {
return ComparisonChain.start()
.compare(o1.value, o2.value, Ordering.natural().nullsFirst()).result();
}
};
} else {
this.indexedComparator = new Comparator<RowIndexedDateValue>() {
@Override
public int compare(final RowIndexedDateValue o1, final RowIndexedDateValue o2) {
return ComparisonChain.start()
.compare(o1.value, o2.value, Ordering.from(comparator).nullsFirst()).result();
}
};
}
}
public int compareTo(VersionNumber other) {
if (major != other.major) {
return major - other.major;
}
if (minor != other.minor) {
return minor - other.minor;
}
if (micro != other.micro) {
return micro - other.micro;
}
if (patch != other.patch) {
return patch - other.patch;
}
return Ordering.natural().nullsLast().compare(toLowerCase(qualifier), toLowerCase(other.qualifier));
}
/** Sort map by value (lowest first) */
public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortMapByValueAscending(
final Map<K, V> map) {
final Ordering<K> valueThenKeyComparator = Ordering.natural()
.onResultOf(Functions.forMap(map))
.compound(Ordering.<K> natural());
return ImmutableSortedMap.copyOf(map, valueThenKeyComparator);
}
@Test
public void run() throws IOException {
if (updateDump) {
logger.info("Updating dump for " + apkFile);
} else {
logger.info("Running regression test for " + apkFile);
}
SmaliClassDetailLoader.fromFramework(FRAMEWORK_CLASSES_FOLDER, API_LEVEL).loadAll(scope);
SmaliClassDetailLoader.fromApkFile(new ZipFile(apkFile), API_LEVEL, true).loadAll(scope);
List<ClassInfo> sortedClasses = Ordering.usingToString().sortedCopy(scope.getAllClasses());
for (ClassInfo c : sortedClasses) {
if (c.isFrameworkClass()) {
continue;
}
handleEntry(c.toString());
if (c.isMissing()) {
handleEntry("\t(missing class)");
continue;
}
List<MethodInfo> sortedMethods = Ordering.usingToString().sortedCopy(c.getAllMethods());
for (MethodInfo m : sortedMethods) {
handleEntry("\t" + m);
if (m.insns == null) {
handleEntry("\t\t(no instructions)");
} else {
for (Instruction i : m.insns) {
handleEntry("\t\t" + i);
}
}
}
}
}
public static SourceJar create(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
ImmutableSortedSet<SourcePath> topLevelSrcs,
Optional<String> mavenCoords,
Optional<SourcePath> mavenPomTemplate) {
// Do not package deps by default.
TraversedDeps traversedDeps = TraversedDeps.traverse(params.getBuildDeps(), false);
params = adjustParams(params, traversedDeps);
ImmutableSortedSet<SourcePath> sourcePaths =
FluentIterable.from(traversedDeps.packagedDeps)
.filter(HasSources.class)
.transformAndConcat(HasSources::getSources)
.append(topLevelSrcs)
.toSortedSet(Ordering.natural());
return new SourceJar(
buildTarget,
projectFilesystem,
params,
sourcePaths,
mavenCoords,
mavenPomTemplate,
traversedDeps);
}
private void logStats() {
Ordering<String> a = Ordering.natural().reverse().onResultOf(Functions.forMap(counters)).compound(Ordering.natural());
Map<String, MutableInt> map = ImmutableSortedMap.copyOf(counters, a);
Iterator<Entry<String, MutableInt>> it = map.entrySet().iterator();
if(it.hasNext()) {// it will be empty if pipeline is run on empty collection
Entry<String, MutableInt> mostFrequentAnno = it.next();
LOGGER.info("[{}] {}: {} ", statName, mostFrequentAnno.getKey(), mostFrequentAnno.getValue().intValue());
}
}
/** Sort map by value (highest first) */
public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortMapByValueDescending(
final Map<K, V> map) {
final Ordering<K> valueThenKeyComparator = Ordering.natural().reverse()
.onResultOf(Functions.forMap(map))
.compound(Ordering.<K> natural().reverse());
return ImmutableSortedMap.copyOf(map, valueThenKeyComparator);
}
@Test
public void testExtractIgnorePaths() {
Config config =
ConfigBuilder.createFromText("[project]", "ignore = .git, foo, bar/, baz//, a/b/c");
Path rootPath = tmp.getRoot();
ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(rootPath, config);
ImmutableSet<Path> ignorePaths =
FluentIterable.from(filesystem.getIgnorePaths())
.filter(RecursiveFileMatcher.class)
.transform(recursiveFileMatcher -> recursiveFileMatcher.getPath().getPath())
.toSet();
assertThat(
ImmutableSortedSet.copyOf(Ordering.natural(), ignorePaths),
equalTo(
ImmutableSortedSet.of(
filesystem.getBuckPaths().getBuckOut(),
filesystem.getBuckPaths().getTrashDir(),
Paths.get(".idea"),
Paths.get(
System.getProperty(
DefaultProjectFilesystemFactory.BUCK_BUCKD_DIR_KEY, ".buckd")),
filesystem.getBuckPaths().getCacheDir(),
Paths.get(".git"),
Paths.get("foo"),
Paths.get("bar"),
Paths.get("baz"),
Paths.get("a/b/c"))));
}
@Override
public int compareTo(LayTile o) {
return ComparisonChain.start()
.compare(this.type, o.type)
.compare(this.specialProperty, o.specialProperty, Ordering.natural().nullsLast())
.result()
;
}
private List<Task> doFindIncompleteForAndCreatedOnBefore(
final Person personAssignedTo,
final LocalDateTime createdOn) {
final List<Task> tasks = repositoryService.allMatches(
new QueryDefault<>(
Task.class,
"findIncompleteByPersonAssignedToAndCreatedOnBefore",
"personAssignedTo", personAssignedTo,
"createdOn", createdOn));
Comparator<Task> comparator = Comparator.comparing(Task::getPriority, Ordering.natural().nullsLast())
.thenComparing(Task::getCreatedOn, Ordering.natural().nullsLast().reverse());
tasks.sort(comparator);
return tasks;
}
public CommitLogReplayer()
{
this.keyspacesRecovered = new NonBlockingHashSet<Keyspace>();
this.futures = new ArrayList<Future<?>>();
this.buffer = new byte[4096];
this.invalidMutations = new HashMap<UUID, AtomicInteger>();
// count the number of replayed mutation. We don't really care about atomicity, but we need it to be a reference.
this.replayedCount = new AtomicInteger();
this.checksum = new PureJavaCrc32();
// compute per-CF and global replay positions
cfPositions = new HashMap<UUID, ReplayPosition>();
Ordering<ReplayPosition> replayPositionOrdering = Ordering.from(ReplayPosition.comparator);
for (ColumnFamilyStore cfs : ColumnFamilyStore.all())
{
// it's important to call RP.gRP per-cf, before aggregating all the positions w/ the Ordering.min call
// below: gRP will return NONE if there are no flushed sstables, which is important to have in the
// list (otherwise we'll just start replay from the first flush position that we do have, which is not correct).
ReplayPosition rp = ReplayPosition.getReplayPosition(cfs.getSSTables());
// but, if we've truncted the cf in question, then we need to need to start replay after the truncation
ReplayPosition truncatedAt = SystemKeyspace.getTruncatedPosition(cfs.metadata.cfId);
if (truncatedAt != null)
rp = replayPositionOrdering.max(Arrays.asList(rp, truncatedAt));
cfPositions.put(cfs.metadata.cfId, rp);
}
globalPosition = replayPositionOrdering.min(cfPositions.values());
logger.debug("Global replay position is {} from columnfamilies {}", globalPosition, FBUtilities.toString(cfPositions));
}
@Override
public int compareTo(FlowTraceHop o) {
return Comparator.comparing(FlowTraceHop::getEdge)
.thenComparing(
FlowTraceHop::getTransformedFlow, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(FlowTraceHop::getRoutes, Comparators.lexicographical(Ordering.natural()))
.thenComparing(FlowTraceHop::getFilterIn, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(FlowTraceHop::getFilterOut, Comparator.nullsFirst(Comparator.naturalOrder()))
.compare(this, o);
}
@Test
public void testArrayListBenchmarks()
throws InstantiationException, IllegalAccessException {
ArrayListLongPoint state = new ArrayListLongPoint();
state.size = 1000;
state.setup();
state.iterate(bh);
state.sort();
state.shuffle();
state.sort();
assertTrue(Ordering.natural().isOrdered(state.list));
}
@Override
public int compareTo(AlphabeticChooserScore o) {
if (o==null) return -1;
return ComparisonChain.start()
// invert the order where we prefer higher values
.compare(o.priority, this.priority)
.compare(o.versionBias, this.versionBias)
.compare(o.brooklynVersion, this.brooklynVersion,
Ordering.from(NaturalOrderComparator.INSTANCE).nullsFirst())
.compare(o.statePriority, this.statePriority)
.compare(this.nodeId, o.nodeId, Ordering.usingToString().nullsLast())
.result();
}
@Test
public void order_by_object_field () {
List<GlassWare> beerGlasses = Lists.newArrayList(
new GlassWare("Flute Glass", "Enhances and showcases..."),
new GlassWare("Pilsner Glass (or Pokal)", "showcases color, ..."),
new GlassWare("Pint Glass", "cheap to make..."),
new GlassWare("Goblet (or Chalice)", "Eye candy..."),
new GlassWare("Mug (or Seidel, Stein)", "Easy to drink..."),
new GlassWare(null, null)
);
Ordering<GlassWare> byGlassWareName = Ordering.natural().nullsFirst()
.onResultOf(new Function<GlassWare, String>() {
public String apply(GlassWare glassWare) {
return glassWare.getName();
}
});
GlassWare firstBeerGlass = byGlassWareName.min(beerGlasses);
// first element will be null
assertNull(firstBeerGlass.getName());
GlassWare lastBeerGlass = byGlassWareName.max(beerGlasses);
assertEquals("Pint Glass", lastBeerGlass.getName());
}
/** @return {@link Ordering} which compares both values of the {@link Pair}s, with the second taking precedence. */
public static <X extends Comparable<? super X>, Y extends Comparable<? super Y>> Ordering<Pair<X,Y>> secondThenFirstComparator() {
return new Ordering<Pair<X,Y>>() {
@Override public int compare(Pair<X, Y> o1, Pair<X, Y> o2) {
int k = Compare.compare(o1.second, o2.second);
if (k == 0)
k = Compare.compare(o1.first, o2.first);
return k;
}
};
}