Example usage for com.google.common.collect Ordering natural

List of usage examples for com.google.common.collect Ordering natural

Introduction

In this page you can find the example usage for com.google.common.collect Ordering natural.

Prototype

@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") 
public static <C extends Comparable> Ordering<C> natural() 

Source Link

Document

Returns a serializable ordering that uses the natural order of the values.

Usage

From source file:com.facebook.buck.android.GenerateStringResources.java

@Override
public SortedSet<BuildRule> getBuildDeps() {
    return BuildableSupport.deriveDeps(this, ruleFinder)
            .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
}

From source file:org.jetbrains.jet.plugin.navigation.NavigationTestUtils.java

public static void assertGotoSymbol(@NotNull Project project, @NotNull Editor editor) {

    List<String> searchTextList = InTextDirectivesUtils.findListWithPrefix("// SEARCH_TEXT:",
            editor.getDocument().getText());
    Assert.assertFalse("There's no search text in test data file given. Use '// SEARCH_TEXT:' directive",
            searchTextList.isEmpty());/*from w  ww .  jav a 2 s.c  o m*/

    List<String> expectedReferences = InTextDirectivesUtils.findListWithPrefix("// REF:",
            editor.getDocument().getText());

    String searchText = searchTextList.get(0);

    List<Object> elementsByName = new ArrayList<Object>();

    GotoSymbolModel2 model = new GotoSymbolModel2(project);
    String[] names = model.getNames(false);
    for (String name : names) {
        if (name != null && name.startsWith(searchText)) {
            elementsByName.addAll(Arrays
                    .asList(model.getElementsByName(name, false, name + "*", new ProgressIndicatorBase())));
        }
    }

    List<String> renderedElements = Lists.transform(elementsByName, new Function<Object, String>() {
        @Override
        public String apply(@Nullable Object element) {
            Assert.assertNotNull(element);
            Assert.assertTrue(element instanceof PsiElement);
            return ReferenceUtils.renderAsGotoImplementation((PsiElement) element);
        }
    });

    UsefulTestCase.assertOrderedEquals(Ordering.natural().sortedCopy(renderedElements), expectedReferences);
}

From source file:org.eclipse.tracecompass.internal.segmentstore.core.treemap.TreeMapStore.java

/**
 * Constructor/*w  w w  . j a v  a 2s  . c o  m*/
 */
public TreeMapStore() {
    /*
     * For the start times index, the "key comparator" will compare the
     * start times as longs directly. This is the primary comparator for its
     * tree map.
     *
     * The secondary "value" comparator will check the end times first, and
     * in the event of a tie, defer to the ISegment's Comparable
     * implementation, a.k.a. its natural ordering.
     *
     * The same is done for the end times index, but swapping the first two
     * comparators instead.
     */
    fStartTimesIndex = TreeMultimap.create(SegmentComparators.LONG_COMPARATOR,
            Ordering.from(SegmentComparators.INTERVAL_END_COMPARATOR).compound(Ordering.natural()));

    fEndTimesIndex = TreeMultimap.create(SegmentComparators.LONG_COMPARATOR,
            Ordering.from(SegmentComparators.INTERVAL_START_COMPARATOR).compound(Ordering.natural()));

    fSize = 0;
}

From source file:com.github.praxissoftware.maven.plugins.GenerateFeaturesMojo.java

@SuppressWarnings("unchecked")
@Override/*from   ww w .  j a  v a 2 s  .co  m*/
public void execute() throws MojoExecutionException {
    Writer out = null;
    try {

        // Get the template text from the jar's resources.
        final InputSupplier<InputStreamReader> supplier = CharStreams
                .newReaderSupplier(new InputSupplier<InputStream>() {
                    @Override
                    public InputStream getInput() throws IOException {
                        return getClass().getClassLoader().getResourceAsStream("features.mustache.xml");
                    }
                }, Charsets.UTF_8);
        final String template = CharStreams.toString(supplier);

        // Create the mustache factory from the loaded template.
        final Mustache mustache = new MustacheBuilder().parse(template, "features.mustache.xml");

        // Establish output stream.
        final File featureFile = setUpFile(outputFile);
        out = new FileWriter(featureFile);

        // Build context.
        final Map<String, Object> context = convert(project.getArtifact());

        final List<Map<String, Object>> dependencies = Lists.newArrayList();
        for (final Artifact dependency : Ordering.natural().onResultOf(new SortByCoordinates())
                .sortedCopy(Iterables.filter((Collection<Artifact>) project.getDependencyArtifacts(),
                        new ArtifactsWeWant()))) {
            dependencies.add(convert(dependency));
        }
        context.put("dependencies", dependencies);

        getLog().info("Writing feature to " + outputFile.getAbsolutePath());

        // Render template.
        mustache.execute(out, context);
    } catch (final Exception e) {
        Throwables.propagateIfInstanceOf(e, MojoExecutionException.class);
        Throwables.propagateIfPossible(e);
        throw new MojoExecutionException("Unable to generate features.xml.", e);
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:com.gradleware.tooling.testing.GradleVersionProvider.java

/**
 * Returns a list of {@code GradleVersion} that fall into the range covered by this provider.
 *
 * @return the matching Gradle versions falling into the covered range, never null
 *///from   ww  w  .  j  a  v  a 2 s  .com
public ImmutableList<GradleVersion> getConfiguredGradleVersions() {
    String pattern = this.versionRangePattern.get();
    LOG.debug("Applying version range pattern '{}'", pattern);

    // add matching versions to set to avoid potential duplicates (e.g. when current == latest)
    ImmutableSet<GradleVersion> configuredGradleVersions;
    if (pattern.equals(ALL)) {
        configuredGradleVersions = ImmutableSet.<GradleVersion>builder().add(GradleVersion.current())
                .addAll(this.releasedVersions.getAll()).build();
    } else if (pattern.equals(LATEST)) {
        configuredGradleVersions = ImmutableSet.<GradleVersion>builder().add(GradleVersion.current())
                .add(this.releasedVersions.getLatest()).build();
    } else if (pattern.matches("^\\d.*$")) {
        configuredGradleVersions = FluentIterable.from(Splitter.on(',').split(pattern))
                .transform(new Function<String, GradleVersion>() {
                    @Override
                    public GradleVersion apply(String input) {
                        return GradleVersion.version(input);
                    }
                }).toSet();
    } else {
        throw new RuntimeException("Invalid range pattern: " + pattern
                + " (valid values: 'all', 'latest', or comma separated list of versions)");
    }

    return Ordering.natural().reverse().immutableSortedCopy(configuredGradleVersions);
}

From source file:com.spotify.cassandra.opstools.DynamicSnitchDumper.java

private static Map<InetAddress, Double> sortMap(Map<InetAddress, Double> scores) {
    return ImmutableSortedMap.copyOf(scores,
            Ordering.natural().onResultOf(Functions.forMap(scores)).compound(new Comparator<InetAddress>() {
                @Override/* w  ww.  j a  v  a  2s . c  om*/
                public int compare(InetAddress o1, InetAddress o2) {
                    return o1.toString().compareTo(o2.toString());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            }));
}

From source file:org.eclipse.recommenders.jayes.transformation.LatentDeterministicDecomposition.java

private List<double[]> getBest(final Map<double[], Integer> counts, int basisSize, int minTotalCounts) {
    PriorityQueue<double[]> q = new PriorityQueue<double[]>(basisSize,
            Ordering.natural().onResultOf(Functions.forMap(counts)));

    for (Entry<double[], Integer> e : counts.entrySet()) {
        if (q.isEmpty() || q.size() < basisSize) {
            q.add(e.getKey());/*from w  ww  . j av a2s . c o m*/
        } else {
            double[] head = q.peek();
            if (counts.get(head) < counts.get(e.getKey())) {
                q.remove();
                q.add(e.getKey());
            }
        }
    }

    int totalcounts = 0;
    for (double[] v : q) {
        totalcounts += counts.get(v);
    }
    if (totalcounts < minTotalCounts)
        return null;

    return new ArrayList<double[]>(q);
}

From source file:io.v.baku.toolkit.bind.PrefixBindingBuilder.java

/**
 * For comparable {@code T}, default to natural ordering on values. Otherwise, default to
 * natural ordering on row names./*from   www.  j  a  v a  2  s.  co m*/
 */
private Ordering<? super RxTable.Row<? extends T>> getDefaultOrdering() {
    if (mOrdering == null && Comparable.class.isAssignableFrom(getType())) {
        return Ordering.natural().onResultOf(r -> (Comparable) r.getValue());
    } else {
        return Ordering.natural().onResultOf(RxTable.Row::getRowName);
    }
}

From source file:org.eclipse.sirius.business.api.action.PrintInterpreterVariablesAction.java

private void printVariables(String title, SortedMap<String, Object> allVariables) {
    if (allVariables.isEmpty()) {
        // CHECKSTYLE:OFF
        System.out.println("[" + title + "] no variables available."); //$NON-NLS-1$ //$NON-NLS-2$
        // CHECKSTYLE:ON
    } else {//from   w ww .  j  a v a 2  s  .  c o m
        int maxLength = Ordering.natural().onResultOf(new Function<String, Integer>() {
            @Override
            public Integer apply(String from) {
                return from.length();
            }
        }).max(allVariables.keySet()).length();
        // CHECKSTYLE:OFF
        System.out.println("[" + title + "] variables available:"); //$NON-NLS-1$ //$NON-NLS-2$
        int i = 1;
        for (Map.Entry<String, Object> variable : allVariables.entrySet()) {
            System.out.print("  " + i++ + ". " + variable.getKey()); //$NON-NLS-1$ //$NON-NLS-2$
            for (int j = 0; j < (maxLength - variable.getKey().length()); j++) {
                System.out.print(" "); //$NON-NLS-1$
            }
            System.out.println(": " + variable.getValue()); //$NON-NLS-1$
        }
        System.out.println();
        // CHECKSTYLE:ON
    }
}

From source file:org.opendaylight.groupbasedpolicy.dto.RuleGroup.java

@Override
public int compareTo(RuleGroup o) {
    return ComparisonChain.start().compare(order, o.order, Ordering.natural().nullsLast())
            .compare(relatedSubject.getValue(), o.relatedSubject.getValue(), Ordering.natural().nullsLast())
            .result();/*from w w w.  j a  v  a  2  s.  co m*/
}