Java Code Examples for com.google.common.collect.Ordering#sortedCopy()

The following examples show how to use com.google.common.collect.Ordering#sortedCopy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SortEnum.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@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));

}
 
Example 2
Source File: SortEnum.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 3
Source File: CheckContextsGenerator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
      }
    }
  }
}
 
Example 4
Source File: CheckExtensionHelperManager.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
    }
  }
}
 
Example 5
Source File: QueryShuffleTransformation.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: AllAtOnceExecutionSchedule.java    From presto with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 7
Source File: GuavaOrderingExamplesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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));
}
 
Example 8
Source File: GuavaFunctionalExamplesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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));
}
 
Example 9
Source File: GroupResourceService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: ComputeResourceService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: DefaultDirectedGraph.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** 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) + ")";
}
 
Example 12
Source File: CheckResourceUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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())));
}
 
Example 13
Source File: PlayerManager.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 14
Source File: DefaultDirectedGraph.java    From Quicksql with MIT License 5 votes vote down vote up
/** 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) + ")";
}
 
Example 15
Source File: LogDirectoriesScanner.java    From singer with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: LogStream.java    From singer with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 17
Source File: DefaultDirectedGraph.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** 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) + ")";
}
 
Example 18
Source File: Classification.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
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);
}
 
Example 19
Source File: NearestNeighborModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
@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;
}
 
Example 20
Source File: SessionsByTimeslot.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
@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");
}