下面列出了com.google.common.collect.Ordering#sortedCopy ( ) 实例代码,或者点击链接到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);
}
}
}
}
/**
* Sorts the plug-in extensions alphabetically by extension point ID and then by extension ID (and name in case the IDs are equal or null).
*
* @param pluginModel
* the plugin model
* @param monitor
* the monitor
* @throws CoreException
* the core exception
*/
public void sortAllExtensions(final IPluginModelBase pluginModel, final IProgressMonitor monitor) throws CoreException {
Ordering<IPluginExtension> ordering = Ordering.from((a, b) -> ComparisonChain.start().compare(a.getPoint(), b.getPoint()).compare(a.getId(), b.getId(), Ordering.natural().nullsLast()).compare(a.getName(), b.getName(), Ordering.natural().nullsLast()).result());
List<IPluginExtension> catalogExtensions = Lists.newArrayList(findAllExtensions(pluginModel));
List<IPluginExtension> orderedExtensions = ordering.sortedCopy(catalogExtensions);
if (catalogExtensions.equals(orderedExtensions)) {
return;
}
for (int i = 0; i < orderedExtensions.size(); i++) {
IPluginExtension expected = orderedExtensions.get(i);
IPluginExtension actual = catalogExtensions.get(i);
if (!Objects.equals(actual, expected)) {
// IExtensions#swap() doesn't work; see https://bugs.eclipse.org/bugs/show_bug.cgi?id=506831
// pluginModel.getExtensions().swap(expected, actual);
for (int j = i; j < catalogExtensions.size(); j++) {
pluginModel.getExtensions().remove(catalogExtensions.get(j));
}
for (int j = i; j < orderedExtensions.size(); j++) {
pluginModel.getExtensions().add(orderedExtensions.get(j));
}
break;
}
}
}
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;
}
@Test
public void create_drop_down() {
Ordering<Fruit> byFruitAlphabetical = Ordering.explicit(Fruit.APPLE,
Fruit.BANANAS, Fruit.CHERRIES, Fruit.ORANGE);
List<Fruit> dropDown = byFruitAlphabetical.sortedCopy(Arrays
.asList(Fruit.values()));
logger.info(dropDown);
assertThat(
dropDown,
contains(Fruit.APPLE, Fruit.BANANAS, Fruit.CHERRIES,
Fruit.ORANGE));
}
@Test
public void sort_enum_with_guava() {
Ordering<Fruit> byFruitAlphabetical = Ordering.explicit(Fruit.APPLE,
Fruit.BANANAS, Fruit.CHERRIES, Fruit.ORANGE);
List<Fruit> fruitAlphabetical = byFruitAlphabetical
.sortedCopy(RANDOM_FRUIT);
logger.info(fruitAlphabetical);
assertThat(
fruitAlphabetical,
contains(Fruit.APPLE, Fruit.BANANAS, Fruit.CHERRIES,
Fruit.CHERRIES, Fruit.ORANGE, Fruit.ORANGE));
}
/** Returns the string representation of this graph, using the given
* orderings to ensure that the output order of vertices and edges is
* deterministic. */
private String toString(Ordering<V> vertexOrdering,
Ordering<E> edgeOrdering) {
return "graph("
+ "vertices: " + vertexOrdering.sortedCopy(vertexMap.keySet())
+ ", edges: " + edgeOrdering.sortedCopy(edges) + ")";
}
public AllAtOnceExecutionSchedule(Collection<SqlStageExecution> stages)
{
requireNonNull(stages, "stages is null");
List<PlanFragmentId> preferredScheduleOrder = getPreferredScheduleOrder(stages.stream()
.map(SqlStageExecution::getFragment)
.collect(toImmutableList()));
Ordering<SqlStageExecution> ordering = Ordering.explicit(preferredScheduleOrder)
.onResultOf(PlanFragment::getId)
.onResultOf(SqlStageExecution::getFragment);
schedulingStages = new LinkedHashSet<>(ordering.sortedCopy(stages));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void initialize() throws IOException {
SingerLogConfig singerLogConfig = singerLog.getSingerLogConfig();
String regexStr = fileNamePrefix;
File logDir = new File(singerLogConfig.getLogDir());
if (singerLogConfig.getFilenameMatchMode() == FileNameMatchMode.PREFIX) {
regexStr += ".*";
}
LOG.info("Matching files under {} with filter {}", logDir, regexStr);
FileFilter fileFilter = new RegexFileFilter(regexStr);
File[] files = logDir.listFiles(fileFilter);
// Sort the file first by last_modified timestamp and then by name in case two files have
// the same mtime due to precision (mtime is up to seconds).
Ordering ordering = Ordering.from(
new CompositeFileComparator(
LastModifiedFileComparator.LASTMODIFIED_COMPARATOR, NameFileComparator.NAME_REVERSE));
List<File> logFiles = ordering.sortedCopy(Arrays.asList(files));
LOG.info(files.length + " files matches the regex '{}'", regexStr);
synchronized (logFilesInfoLock) {
logFilePaths.clear();
logFilePathsIndex.clear();
for (File entry : logFiles) {
long inode = SingerUtils.getFileInode(entry.toPath());
append(new LogFile(inode), entry.toPath().toString());
}
}
OpenTsdbMetricConverter.incr(SingerMetrics.LOGSTREAM_INITIALIZE, 1,
"log=" + logStreamName, "host=" + SingerUtils.getHostname());
}
public List<File> getFilesInSortedOrder(Path dirPath) {
File[] files = dirPath.toFile().listFiles((FileFilter) FileFileFilter.FILE);
// Sort the file first by last_modified timestamp and then by name in case two files have
// the same mtime due to precision (mtime is up to seconds).
Ordering<File> ordering = Ordering.from(new SingerUtils.LogFileComparator());
List<File> logFiles = ordering.sortedCopy(Arrays.asList(files));
return logFiles;
}
/** Returns the string representation of this graph, using the given
* orderings to ensure that the output order of vertices and edges is
* deterministic. */
private String toString(Ordering<V> vertexOrdering,
Ordering<E> edgeOrdering) {
return "graph("
+ "vertices: " + vertexOrdering.sortedCopy(vertexMap.keySet())
+ ", edges: " + edgeOrdering.sortedCopy(edges) + ")";
}
private void reorder(Comparator<Player> comparator) {
Ordering<Player> ordering = Ordering.from(comparator);
List<Player> newOrder = ordering.sortedCopy(playerOrder.view());
playerOrder.setTo(newOrder);
for (int i = 0; i < newOrder.size(); i++) {
Player player = newOrder.get(i);
player.setIndex(i);
}
}
/**
* Looks up all exported grammars.
*
* @return an iterable of grammar
*/
public List<Grammar> getGrammars() {
Iterable<Grammar> result = allGrammars();
Ordering<Grammar> byNameOrdering = new Ordering<Grammar>() {
@Override
public int compare(final Grammar left, final Grammar right) {
return Ordering.<String> natural().compare(new GrammarHelper(left).getLabelName(), new GrammarHelper(right).getLabelName());
}
};
return byNameOrdering.sortedCopy(Sets.newHashSet(Iterables.filter(result, Predicates.notNull())));
}
/** Returns the string representation of this graph, using the given
* orderings to ensure that the output order of vertices and edges is
* deterministic. */
private String toString(Ordering<V> vertexOrdering,
Ordering<E> edgeOrdering) {
return "graph("
+ "vertices: " + vertexOrdering.sortedCopy(vertexMap.keySet())
+ ", edges: " + edgeOrdering.sortedCopy(edges) + ")";
}
private Iterable<Group> getOrderedCopy(Iterable<Group> groups) {
Ordering<Group> byLengthOrdering = new Ordering<>() {
@Override
public int compare(Group left, Group right) {
return Ints.compare(left.getInstances().size(), right.getInstances().size());
}
};
return byLengthOrdering.sortedCopy(groups);
}
private Iterable<Group> getOrderedCopy(Iterable<Group> groups) {
Ordering<Group> byLengthOrdering = new Ordering<>() {
@Override
public int compare(Group left, Group right) {
return Ints.compare(left.getInstancesSize(), right.getInstancesSize());
}
};
return byLengthOrdering.sortedCopy(groups);
}
@Test
public final void whenUsingAnIntermediaryFunctionToOrder_thenCorerctlyOrderedInAlphabeticalOrder() {
final List<Integer> numbersToSort = Arrays.asList(2, 1, 11, 100, 8, 14);
final Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
final List<Integer> inAlphabeticalOrder = ordering.sortedCopy(numbersToSort);
final List<Integer> correctAlphabeticalOrder = Lists.newArrayList(1, 100, 11, 14, 2, 8);
assertThat(correctAlphabeticalOrder, equalTo(inAlphabeticalOrder));
}
@Test
public final void givenListOfNumbers_whenRunningAToStringFunctionThenSorting_thenCorrect() {
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
final Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
final List<Integer> sortedCopy = ordering.sortedCopy(toSort);
final List<Integer> expected = Lists.newArrayList(1, 100, 11, 14, 2, 8);
assertThat(expected, equalTo(sortedCopy));
}
static
public <K, V extends Number> List<Map.Entry<K, Value<V>>> getWinnerList(Type type, Collection<Map.Entry<K, Value<V>>> entries){
Ordering<Map.Entry<K, Value<V>>> ordering = (Classification.<K, V>createOrdering(type)).reverse();
return ordering.sortedCopy(entries);
}
@Override
protected <V extends Number> Map<FieldName, AffinityDistribution<V>> evaluateMixed(ValueFactory<V> valueFactory, EvaluationContext context){
NearestNeighborModel nearestNeighborModel = getModel();
Table<Integer, FieldName, FieldValue> table = getTrainingInstances();
List<InstanceResult<V>> instanceResults = evaluateInstanceRows(valueFactory, context);
Ordering<InstanceResult<V>> ordering = (Ordering.natural()).reverse();
List<InstanceResult<V>> nearestInstanceResults = ordering.sortedCopy(instanceResults);
Integer numberOfNeighbors = nearestNeighborModel.getNumberOfNeighbors();
if(numberOfNeighbors == null){
throw new MissingAttributeException(nearestNeighborModel, PMMLAttributes.NEARESTNEIGHBORMODEL_NUMBEROFNEIGHBORS);
}
nearestInstanceResults = nearestInstanceResults.subList(0, numberOfNeighbors);
Function<Integer, String> function = new Function<Integer, String>(){
@Override
public String apply(Integer row){
return row.toString();
}
};
FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable();
if(instanceIdVariable != null){
function = createIdentifierResolver(instanceIdVariable, table);
}
Map<FieldName, AffinityDistribution<V>> results = new LinkedHashMap<>();
List<TargetField> targetFields = getTargetFields();
for(TargetField targetField : targetFields){
FieldName name = targetField.getFieldName();
Object value;
OpType opType = targetField.getOpType();
switch(opType){
case CONTINUOUS:
value = calculateContinuousTarget(valueFactory, name, nearestInstanceResults, table);
break;
case CATEGORICAL:
value = calculateCategoricalTarget(valueFactory, name, nearestInstanceResults, table);
break;
default:
throw new InvalidElementException(nearestNeighborModel);
}
value = TypeUtil.parseOrCast(targetField.getDataType(), value);
AffinityDistribution<V> result = createAffinityDistribution(instanceResults, function, value);
results.put(name, result);
}
return results;
}
@Override
public void run() {
long testStartTime = System.nanoTime();
marktime = System.nanoTime();
try {
timelog("Beginning Sessions By TimeSlot...");
ConferenceGraph graph = new ConferenceGraph();
Session session = Factory.getSession(SessionType.CURRENT);
String myName = session.getEffectiveUserName();
Attendee att = graph.getAttendee(myName, false);
Ordering<TimeSlot> byStart = new Ordering<TimeSlot>() {
@Override
public int compare(final TimeSlot t1, final TimeSlot t2) {
return t1.getStartTime().compareTo(t2.getStartTime());
}
};
Iterable<TimeSlot> times = graph.getTimeSlots();
List<TimeSlot> timesSorted = byStart.sortedCopy(times);
for (TimeSlot ts : timesSorted) {
System.out.println("Sessions running from " + DATE_FORMAT.format(ts.getStartTime().getTime()) + " to "
+ DATE_FORMAT.format(ts.getEndTime().getTime()));
System.out.println(ts.getDuration());
Iterable<Event> presentations = ts.getEvents();
for (Event evt : presentations) {
if (evt instanceof Presentation) {
Presentation pres = (Presentation) evt;
System.out.println(pres.getSessionId() + ": " + pres.getTitle());
}
}
}
} catch (Throwable t) {
t.printStackTrace();
}
long testEndTime = System.nanoTime();
System.out.println("Completed " + getClass().getSimpleName() + " run in " + ((testEndTime - testStartTime) / 1000000) + " ms");
}