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

The following examples show how to use com.google.common.collect.Ordering#natural() . 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: ImmutableSortedSetTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testImmutableSortedSet() {
  ImmutableSortedSet<String> set = newSet();
  assertEquals(3, set.size());
  assertFalse(set.isEmpty());
  assertEquals("bar", set.getMinEntry());
  assertEquals("foo", set.getMaxEntry());
  assertEquals("bar", set.getPredecessorEntry("baz"));
  assertTrue(set.contains("foo"));
  assertFalse(set.contains("not found"));
  assertEquals(set.hashCode(), set.hashCode());
  assertEquals(set, set);

  ImmutableSortedSet<String> set2 = newSet();
  assertEquals(set.hashCode(), set2.hashCode());
  assertEquals(set, set2);

  List<String> original = new ArrayList<>();
  Collections.addAll(original, "abc", "mno", "pqr");
  set2 = new ImmutableSortedSet<>(original, Ordering.<String>natural());
  assertNotEquals(set.hashCode(), set2.hashCode());
  assertNotEquals(set, set2);
}
 
Example 2
Source File: LocationBoundingVisitor.java    From closure-stylesheets with Apache License 2.0 6 votes vote down vote up
@Override
public void enter(CssNode n) {
  SourceCodeLocation loc = n.getSourceCodeLocation();
  if (loc == null || loc.isUnknown()) {
    return;
  }
  if (result == null || result.isUnknown()) {
    result = loc;
  } else {
    Ordering<SourceCodePoint> o = Ordering.natural();
    SourceCodePoint lowerBound = o.min(result.getBegin(), loc.getBegin());
    SourceCodePoint upperBound = o.max(result.getEnd(), loc.getEnd());
    result = new SourceCodeLocationBuilder()
        .setSourceCode(result.getSourceCode())
        .setBeginLocation(lowerBound)
        .setEndLocation(upperBound)
        .getSourceCodeLocation();
  }
}
 
Example 3
Source File: OrderingByPosition.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private OrderingByPosition (int position, boolean reverse, @Nullable Boolean nullFirst) {
    this.position = position;

    // note, that we are reverse for the queue so this conditional is by intent
    Ordering<Comparable> ordering;
    nullFirst = nullFirst != null ? !nullFirst : null; // swap because queue is reverse
    if (reverse) {
        ordering = Ordering.natural();
        if (nullFirst == null || !nullFirst) {
            ordering = ordering.nullsLast();
        } else {
            ordering = ordering.nullsFirst();
        }
    } else {
        ordering = Ordering.natural().reverse();
        if (nullFirst == null || nullFirst) {
            ordering = ordering.nullsFirst();
        } else {
            ordering = ordering.nullsLast();
        }
    }
    this.ordering = ordering;
}
 
Example 4
Source File: CommonThreadStateRenderer.java    From buck with Apache License 2.0 6 votes vote down vote up
public ImmutableList<Long> getSortedThreadIds(boolean sortByTime) {
  Comparator<Long> comparator;
  if (sortByTime) {
    comparator =
        new Comparator<Long>() {
          private Comparator<Long> reverseOrdering = Ordering.natural().reverse();

          @Override
          public int compare(Long threadId1, Long threadId2) {
            long elapsedTime1 =
                Objects.requireNonNull(threadInformationMap.get(threadId1)).getElapsedTimeMs();
            long elapsedTime2 =
                Objects.requireNonNull(threadInformationMap.get(threadId2)).getElapsedTimeMs();
            return ComparisonChain.start()
                .compare(elapsedTime1, elapsedTime2, reverseOrdering)
                .compare(threadId1, threadId2)
                .result();
          }
        };
  } else {
    comparator = Ordering.natural();
  }
  return FluentIterable.from(threadInformationMap.keySet()).toSortedList(comparator);
}
 
Example 5
Source File: Router.java    From nomulus with Apache License 2.0 6 votes vote down vote up
static ImmutableSortedMap<String, Route> extractRoutesFromComponent(Class<?> componentClass) {
  ImmutableSortedMap.Builder<String, Route> routes =
      new ImmutableSortedMap.Builder<>(Ordering.natural());
  for (Method method : componentClass.getMethods()) {
    // Make App Engine's security manager happy.
    method.setAccessible(true);
    if (!isDaggerInstantiatorOfType(Runnable.class, method)) {
      continue;
    }
    Action action = method.getReturnType().getAnnotation(Action.class);
    if (action == null) {
      continue;
    }
    @SuppressWarnings("unchecked") // Safe due to previous checks.
    Route route =
        Route.create(
            action,
            (Function<Object, Runnable>) newInstantiator(method),
            method.getReturnType());
    routes.put(action.path(), route);
  }
  return routes.build();
}
 
Example 6
Source File: DiffUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static Map<Integer, ?> iterableToSortedMap(Iterable<?> iterable) {
  // We use a sorted map here so that the iteration across the keySet is consistent.
  ImmutableSortedMap.Builder<Integer, Object> builder =
      new ImmutableSortedMap.Builder<>(Ordering.natural());
  int i = 0;
  for (Object item : Iterables.filter(iterable, Objects::nonNull)) {
    builder.put(i++, item);
  }
  return builder.build();
}
 
Example 7
Source File: ProductMetricsTest.java    From phoenix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void helpTestOrderByNullColumns(boolean nullsFirst) throws Exception {
    long ts = nextTimestamp();
    String tenantId = getOrganizationId();
    String query = "SELECT region " +
                   "FROM PRODUCT_METRICS " + 
                   "WHERE organization_id=? " +
                   "GROUP BY region " +
                   "ORDER BY region nulls " + (nullsFirst ? "first" : "last");

    String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
    Properties props = new Properties(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        initTableValues(tenantId, getSplits(tenantId), ts);
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        
        List<String> expected = Lists.newArrayList(null, R1, R2);
        Ordering<String> regionOrdering = Ordering.natural();
        regionOrdering = nullsFirst ? regionOrdering.nullsFirst() : regionOrdering.nullsLast();
        Collections.sort(expected, regionOrdering);
        
        for (String region : expected) {
            assertTrue(rs.next());
            assertEquals(region, rs.getString(1));
        }
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example 8
Source File: ProductMetricsIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private void helpTestOrderByNullColumns(boolean nullsFirst) throws Exception {
    String tablename=generateUniqueName();
    String tenantId = getOrganizationId();
    String query = "SELECT region " +
            "FROM " +tablename+
            " WHERE organization_id=? " +
            "GROUP BY region " +
            "ORDER BY region nulls " + (nullsFirst ? "first" : "last");

    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        initTableValues(tablename, tenantId, getSplits(tenantId));
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();

        List<String> expected = Lists.newArrayList(null, R1, R2);
        Ordering<String> regionOrdering = Ordering.natural();
        regionOrdering = nullsFirst ? regionOrdering.nullsFirst() : regionOrdering.nullsLast();
        Collections.sort(expected, regionOrdering);

        for (String region : expected) {
            assertTrue(rs.next());
            assertEquals(region, rs.getString(1));
        }
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example 9
Source File: ConfigFeatureFlagTaggedTrimmingTransitionFactory.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public PatchTransition create(Rule rule) {
  NonconfigurableAttributeMapper attrs = NonconfigurableAttributeMapper.of(rule);
  RuleClass ruleClass = rule.getRuleClassObject();
  if (ruleClass.getName().equals(ConfigRuleClasses.ConfigFeatureFlagRule.RULE_NAME)) {
    return new ConfigFeatureFlagTaggedTrimmingTransition(ImmutableSortedSet.of(rule.getLabel()));
  }

  ImmutableSortedSet.Builder<Label> requiredLabelsBuilder =
      new ImmutableSortedSet.Builder<>(Ordering.natural());
  if (attrs.isAttributeValueExplicitlySpecified(attributeName)
      && !attrs.get(attributeName, NODEP_LABEL_LIST).isEmpty()) {
    requiredLabelsBuilder.addAll(attrs.get(attributeName, NODEP_LABEL_LIST));
  }
  if (ruleClass.getTransitionFactory() instanceof ConfigFeatureFlagTransitionFactory) {
    String settingAttribute =
        ((ConfigFeatureFlagTransitionFactory) ruleClass.getTransitionFactory())
            .getAttributeName();
    // Because the process of setting a flag also creates a dependency on that flag, we need to
    // include all the set flags, even if they aren't actually declared as used by this rule.
    requiredLabelsBuilder.addAll(attrs.get(settingAttribute, LABEL_KEYED_STRING_DICT).keySet());
  }

  ImmutableSortedSet<Label> requiredLabels = requiredLabelsBuilder.build();
  if (requiredLabels.isEmpty()) {
    return ConfigFeatureFlagTaggedTrimmingTransition.EMPTY;
  }

  return new ConfigFeatureFlagTaggedTrimmingTransition(requiredLabels);
}
 
Example 10
Source File: ProductMetricsIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private void helpTestOrderByNullColumns(boolean nullsFirst) throws Exception {
    long ts = nextTimestamp();
    String tenantId = getOrganizationId();
    String query = "SELECT region " +
                   "FROM PRODUCT_METRICS " + 
                   "WHERE organization_id=? " +
                   "GROUP BY region " +
                   "ORDER BY region nulls " + (nullsFirst ? "first" : "last");

    String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        initTableValues(tenantId, getSplits(tenantId), ts);
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        
        List<String> expected = Lists.newArrayList(null, R1, R2);
        Ordering<String> regionOrdering = Ordering.natural();
        regionOrdering = nullsFirst ? regionOrdering.nullsFirst() : regionOrdering.nullsLast();
        Collections.sort(expected, regionOrdering);
        
        for (String region : expected) {
            assertTrue(rs.next());
            assertEquals(region, rs.getString(1));
        }
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example 11
Source File: WorldSwitcherPanel.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private int getCompareValue(WorldTableRow row1, WorldTableRow row2, Function<WorldTableRow, Comparable> compareByFn)
{
	Ordering<Comparable> ordering = Ordering.natural();
	if (!ascendingOrder)
	{
		ordering = ordering.reverse();
	}
	ordering = ordering.nullsLast();
	return ordering.compare(compareByFn.apply(row1), compareByFn.apply(row2));
}
 
Example 12
Source File: SortDataTest.java    From power-adapters with Apache License 2.0 5 votes vote down vote up
@Test
public void sizeIndicatesFullyAccessibleRangeWhenNoObserversRegistered() {
    FakeData<Integer> fakeData = new FakeData<>();
    fakeData.insert(0, 1, 2, 3);
    SortData<Integer> sortData = new SortData<>(fakeData, Ordering.<Integer>natural());
    int size = sortData.size();
    for (int i = 0; i < size; i++) {
        sortData.get(i);
    }
}
 
Example 13
Source File: SortDataTest.java    From power-adapters with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mFakeData = new FakeData<>();
    mFakeData.insert(0, 0, 10, 5, 15, 25, 20);
    mSortData = new SortData<>(mFakeData, Ordering.natural());
    mVerifyingObserver = new VerifyingDataObserver(mSortData);
    mSortData.registerDataObserver(mVerifyingObserver);
}
 
Example 14
Source File: WorldSwitcherPanel.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int getCompareValue(WorldTableRow row1, WorldTableRow row2, Function<WorldTableRow, Comparable> compareByFn)
{
	Ordering<Comparable> ordering = Ordering.natural();
	if (!ascendingOrder)
	{
		ordering = ordering.reverse();
	}
	ordering = ordering.nullsLast();
	return ordering.compare(compareByFn.apply(row1), compareByFn.apply(row2));
}
 
Example 15
Source File: AbstractSliceDistributor.java    From datawave with Apache License 2.0 5 votes vote down vote up
public Comparator<S> getComparator(boolean lifo) {
    if (lifo) {
        return (o1, o2) -> {
            // return the reverse order
            return Ordering.natural().compare(o2, o1);
        };
    } else {
        return Ordering.natural();
    }
}
 
Example 16
Source File: TestingHelpers.java    From crate with Apache License 2.0 4 votes vote down vote up
public static <T, K extends Comparable> Matcher<Iterable<? extends T>> isSortedBy(final Function<T, K> extractSortingKeyFunction,
                                                                                  final boolean descending,
                                                                                  @Nullable final Boolean nullsFirst) {
    Ordering<K> ordering = Ordering.natural();
    if (descending) {
        ordering = ordering.reverse();
    }
    if (nullsFirst != null && nullsFirst) {
        ordering = ordering.nullsFirst();
    } else {
        ordering = ordering.nullsLast();
    }
    final Ordering<K> ord = ordering;

    return new TypeSafeDiagnosingMatcher<Iterable<? extends T>>() {
        @Override
        protected boolean matchesSafely(Iterable<? extends T> item, Description mismatchDescription) {
            K previous = null;
            int i = 0;
            for (T elem : item) {
                K current = extractSortingKeyFunction.apply(elem);
                if (previous != null) {
                    if (ord.compare(previous, current) > 0) {
                        mismatchDescription
                            .appendText("element ").appendValue(current)
                            .appendText(" at position ").appendValue(i)
                            .appendText(" is ")
                            .appendText(descending ? "bigger" : "smaller")
                            .appendText(" than previous element ")
                            .appendValue(previous);
                        return false;
                    }
                }
                i++;
                previous = current;
            }
            return true;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("expected iterable to be sorted ");
            if (descending) {
                description.appendText("in DESCENDING order");
            } else {
                description.appendText("in ASCENDING order");
            }
        }
    };
}
 
Example 17
Source File: OspfArea.java    From batfish with Apache License 2.0 4 votes vote down vote up
private Builder(@Nullable Supplier<Long> numberGenerator) {
  _numberGenerator = numberGenerator;
  _interfaces = new ImmutableSortedSet.Builder<>(Ordering.natural());
  _stubType = StubType.NONE;
  _summaries = new ImmutableSortedMap.Builder<>(Ordering.natural());
}
 
Example 18
Source File: PipelineOptionsSelectionDialog.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
protected Comparator getItemsComparator() {
  return Ordering.natural();
}
 
Example 19
Source File: ImmutableSortedSetTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private ImmutableSortedSet<String> newSet() {
  List<String> original = new ArrayList<>();
  Collections.addAll(original, "foo", "bar", "baz");
  return new ImmutableSortedSet<>(original, Ordering.<String>natural());
}
 
Example 20
Source File: PeekOrdering.java    From datawave with Apache License 2.0 4 votes vote down vote up
public static <T extends Comparable<T>> PeekOrdering<T> make() {
    return new PeekOrdering<>(Ordering.<T> natural());
}