类com.google.common.collect.Ordering源码实例Demo

下面列出了怎么用com.google.common.collect.Ordering的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: java-monitoring-client-library   文件: Counter.java
@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();
}
 
源代码2 项目: n4js   文件: OpenTypeSelectionDialog.java
@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());
  }
}
 
源代码4 项目: bazel   文件: FakeStructApi.java
/** 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));
}
 
源代码6 项目: nomulus   文件: TimedTransitionProperty.java
/**
 * 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;
      });
}
 
源代码7 项目: nomulus   文件: DomainCheckFlowTest.java
@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"));
}
 
源代码8 项目: bazel   文件: SdkMavenRepository.java
/**
 * 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());
}
 
源代码9 项目: pinpoint   文件: AdminServiceImpl.java
@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);
}
 
源代码10 项目: incubator-retired-wave   文件: QueryHelper.java
/**
 * 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;
}
 
源代码12 项目: estatio   文件: TaskRepository.java
/**
 * 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;
}
 
源代码13 项目: samantha   文件: FeatureKnnModel.java
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);
}
 
源代码15 项目: metanome-algorithms   文件: DatatypeDate.java
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();
      }

    };
  }
}
 
源代码16 项目: Pushjet-Android   文件: VersionNumber.java
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));
}
 
源代码17 项目: api-mining   文件: CollectionUtil.java
/** 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);
}
 
源代码18 项目: PATDroid   文件: RegTest.java
@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);
                }
            }
        }
    }
}
 
源代码19 项目: buck   文件: MavenUberJar.java
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);
}
 
源代码20 项目: termsuite-core   文件: CasStatCounter.java
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());
	}
}
 
源代码21 项目: tassal   文件: CollectionUtil.java
/** 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);
}
 
源代码22 项目: buck   文件: DefaultProjectFilesystemTest.java
@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"))));
}
 
源代码23 项目: Rails   文件: LayTile.java
@Override
public int compareTo(LayTile o) {
    return ComparisonChain.start()
            .compare(this.type, o.type)
            .compare(this.specialProperty, o.specialProperty, Ordering.natural().nullsLast())
            .result()
    ;
}
 
源代码24 项目: estatio   文件: TaskRepository.java
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;
}
 
源代码25 项目: stratio-cassandra   文件: CommitLogReplayer.java
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));
}
 
源代码26 项目: batfish   文件: FlowTraceHop.java
@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);
}
 
源代码27 项目: unsafe   文件: BenchmarkTest.java
@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));
}
 
源代码28 项目: brooklyn-server   文件: BasicMasterChooser.java
@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();
}
 
源代码29 项目: levelup-java-examples   文件: OrderingExample.java
@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());
}
 
源代码30 项目: Word2VecJava   文件: Pair.java
/** @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;
		}
	};
}
 
 同包方法