Java Code Examples for java.util.Comparator#naturalOrder()

The following examples show how to use java.util.Comparator#naturalOrder() . 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: Column.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public Comparator<DataAccessor> createComparator(int field) {
    if (Comparable.class.isAssignableFrom(type.getJavaClass())) {
        return (o1, o2) -> {
            Comparable l = (Comparable)o1.get(field);
            if (l == null)return -1;
            Comparable r =(Comparable) o2.get(field);
            if (r == null)return 1;
            return l.compareTo(r);
        };
    }else {
        Comparator tComparator = Comparator.naturalOrder();
        return tComparator;
    }
}
 
Example 2
Source File: SortedMergeIteratorTest.java    From stream-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testFirstEmpty() {
    final Stream<Integer> s1 = Stream.of(1, 3, 5, 7);
    final Stream<Integer> s2 = Stream.empty();

    final Iterator<Integer> iterator = new SortedMergeIterator<>(Arrays.asList(s1, s2), Comparator.naturalOrder());
    final List<Integer> output = new ArrayList<>();
    iterator.forEachRemaining(output::add);

    assertEquals(Arrays.asList(1, 3, 5, 7), output);
}
 
Example 3
Source File: OrderbyDocumentQueryTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Test(groups = { "simple" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder",
        retryAnalyzer = RetryAnalyzer.class)
public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception {
    // Get Actual
    String query = String.format("SELECT * FROM c ORDER BY c.propInt %s", sortOrder);

    // Get Expected
    Comparator<Integer> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder();
    Comparator<Integer> validatorComparator = Comparator.nullsFirst(order);
    
    List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator);
    this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100}, expectedResourceIds);
}
 
Example 4
Source File: VersionTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void can_compare_versions_ascending() {
    Comparator<Version> versionComparator = Comparator.naturalOrder();
    List<String> versions = new ArrayList<>(ascendingVersionsAsString);

    for (int i = 0; i < versions.size(); i++) {
        Version baseVersion = Version.parse(versions.get(i));
        for (int j = i + 1; j < versions.size(); j++) {
            Version cmpVersion = Version.parse(versions.get(j));
            assertLower(versionComparator, baseVersion, cmpVersion);
        }
    }
}
 
Example 5
Source File: MergeIteratorTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Test
public void testMerging() {
    Iterator<Integer> it1 = Arrays.asList(1, 3, 5, 7).iterator();
    Iterator<Integer> it2 = Arrays.asList(2, 4, 6).iterator();

    MergeIterator<Integer> mergeIterator = new MergeIterator<>(it1, it2, Comparator.naturalOrder());

    ArrayList<Integer> res = new ArrayList<>();
    while (mergeIterator.hasNext()) {
        res.add(mergeIterator.next());
    }

    assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7), res);
}
 
Example 6
Source File: BasicTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testComposeComparator() {
    // Longer string in front
    Comparator<String> first = (s1, s2) -> s2.length() - s1.length();
    Comparator<String> second = Comparator.naturalOrder();
    Comparator<String> composed = first.thenComparing(second);

    assertTrue(composed.compare("abcdefg", "abcdef") < 0);
    assertTrue(composed.compare("abcdef", "abcdefg") > 0);
    assertTrue(composed.compare("abcdef", "abcdef") == 0);
    assertTrue(composed.compare("abcdef", "ghijkl") < 0);
    assertTrue(composed.compare("ghijkl", "abcdefg") > 0);
}
 
Example 7
Source File: SortedOps.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sort using natural order of {@literal <T>} which must be
 * {@code Comparable}.
 */
OfRef(AbstractPipeline<?, T, ?> upstream) {
    super(upstream, StreamShape.REFERENCE,
          StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED);
    this.isNaturalSort = true;
    // Will throw CCE when we try to sort if T is not Comparable
    @SuppressWarnings("unchecked")
    Comparator<? super T> comp = (Comparator<? super T>) Comparator.naturalOrder();
    this.comparator = comp;
}
 
Example 8
Source File: BasicTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testComposeComparator() {
    // Longer string in front
    Comparator<String> first = (s1, s2) -> s2.length() - s1.length();
    Comparator<String> second = Comparator.naturalOrder();
    Comparator<String> composed = first.thenComparing(second);

    assertTrue(composed.compare("abcdefg", "abcdef") < 0);
    assertTrue(composed.compare("abcdef", "abcdefg") > 0);
    assertTrue(composed.compare("abcdef", "abcdef") == 0);
    assertTrue(composed.compare("abcdef", "ghijkl") < 0);
    assertTrue(composed.compare("ghijkl", "abcdefg") > 0);
}
 
Example 9
Source File: BunchedMapScanTest.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setup() throws InterruptedException, ExecutionException {
    db = FDB.instance().open();
    bmSubspace = DirectoryLayer.getDefault().createOrOpen(db, PathUtil.from(BunchedMapIterator.class.getSimpleName())).get();
    subSubspaces = LongStream.range(0L, 50L).boxed().map(l -> bmSubspace.subspace(Tuple.from(l))).collect(Collectors.toList());
    map = new BunchedMap<>(BunchedTupleSerializer.instance(), Comparator.naturalOrder(), 10);
    keys = LongStream.range(100L, 500L).boxed().map(Tuple::from).collect(Collectors.toList());
    value = Tuple.from(1066L);
}
 
Example 10
Source File: UnionStringsSketchUDAF.java    From incubator-datasketches-hive with Apache License 2.0 4 votes vote down vote up
UnionStringsSketchEvaluator() {
  super(Comparator.naturalOrder(), new ArrayOfStringsSerDe());
}
 
Example 11
Source File: TracerouteTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeliveredToSubnet2() throws IOException {
  NetworkFactory nf = new NetworkFactory();
  Configuration.Builder cb =
      nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS);

  ImmutableSortedMap.Builder<String, Configuration> configs =
      new ImmutableSortedMap.Builder<>(Comparator.naturalOrder());

  Configuration c1 = cb.build();
  configs.put(c1.getHostname(), c1);

  Vrf v1 = nf.vrfBuilder().setOwner(c1).build();

  // set up interface
  Interface i1 =
      nf.interfaceBuilder()
          .setAddress(ConcreteInterfaceAddress.parse("1.0.0.1/24"))
          .setOwner(c1)
          .setVrf(v1)
          .build();

  // set up static route "1.0.0.128/26" -> "1.0.0.2"
  v1.setStaticRoutes(
      ImmutableSortedSet.of(
          StaticRoute.builder()
              .setNextHopInterface(i1.getName())
              .setNextHopIp(Ip.parse("1.0.0.2"))
              .setNetwork(Prefix.parse("1.0.0.128/26"))
              .setAdministrativeCost(1)
              .build()));

  Configuration c2 = cb.build();
  configs.put(c2.getHostname(), c2);

  Vrf v2 = nf.vrfBuilder().setOwner(c2).build();

  // set up interface on N2
  nf.interfaceBuilder()
      .setAddress(ConcreteInterfaceAddress.parse("1.0.0.2/24"))
      .setOwner(c2)
      .setVrf(v2)
      .setProxyArp(true)
      .build();

  Batfish batfish = BatfishTestUtils.getBatfish(configs.build(), _folder);
  batfish.computeDataPlane(batfish.getSnapshot());

  TracerouteQuestion question =
      new TracerouteQuestion(
          c1.getHostname(),
          PacketHeaderConstraints.builder().setDstIp("1.0.0.129").build(),
          false,
          DEFAULT_MAX_TRACES);

  TracerouteAnswerer answerer = new TracerouteAnswerer(question, batfish);
  TableAnswerElement answer = (TableAnswerElement) answerer.answer(batfish.getSnapshot());

  assertThat(
      answer.getRows().getData(),
      everyItem(hasColumn(COL_TRACES, everyItem(hasHops(hasSize(2))), Schema.set(Schema.TRACE))));

  assertThat(
      answer.getRows().getData(),
      everyItem(
          hasColumn(
              COL_TRACES,
              everyItem(hasDisposition(FlowDisposition.DELIVERED_TO_SUBNET)),
              Schema.set(Schema.TRACE))));
}
 
Example 12
Source File: OspfArea.java    From batfish with Apache License 2.0 4 votes vote down vote up
/** Replace all interfaces in the area */
public Builder setInterfaces(@Nonnull Collection<String> interfaces) {
  _interfaces = new ImmutableSortedSet.Builder<>(Comparator.naturalOrder());
  _interfaces.addAll(interfaces);
  return this;
}
 
Example 13
Source File: BasicTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void testNaturalOrderComparator() {
    Comparator<String> comp = Comparator.naturalOrder();

    assertComparisons(stringValues, comp, comparisons);
}
 
Example 14
Source File: BasicTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void testNaturalOrderComparator() {
    Comparator<String> comp = Comparator.naturalOrder();

    assertComparisons(stringValues, comp, comparisons);
}
 
Example 15
Source File: TracerouteTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
private TableAnswerElement testDispositionMultiInterfaces(String mask) throws IOException {
  NetworkFactory nf = new NetworkFactory();
  Configuration.Builder cb =
      nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS);

  ImmutableSortedMap.Builder<String, Configuration> configs =
      new ImmutableSortedMap.Builder<>(Comparator.naturalOrder());

  Configuration c1 = cb.build();
  configs.put(c1.getHostname(), c1);

  Vrf v1 = nf.vrfBuilder().setOwner(c1).build();

  nf.interfaceBuilder()
      .setAddress(ConcreteInterfaceAddress.parse("1.0.0.130/" + mask))
      .setOwner(c1)
      .setVrf(v1)
      .setProxyArp(true)
      .build();

  Interface n1i1 =
      nf.interfaceBuilder()
          .setAddress(ConcreteInterfaceAddress.parse("2.0.0.1/24"))
          .setOwner(c1)
          .setVrf(v1)
          .setProxyArp(true)
          .build();

  v1.setStaticRoutes(
      ImmutableSortedSet.of(
          StaticRoute.builder()
              .setNextHopInterface(n1i1.getName())
              .setNetwork(Prefix.parse("1.0.0.128/24"))
              .setAdministrativeCost(1)
              .build()));

  Configuration c2 = cb.build();
  configs.put(c2.getHostname(), c2);

  Vrf v2 = nf.vrfBuilder().setOwner(c2).build();

  nf.interfaceBuilder()
      .setAddress(ConcreteInterfaceAddress.parse("2.0.0.2/24"))
      .setOwner(c2)
      .setVrf(v2)
      .setProxyArp(true)
      .build();

  Interface n2i1 =
      nf.interfaceBuilder()
          .setAddress(ConcreteInterfaceAddress.parse("1.0.0.129/24"))
          .setOwner(c2)
          .setVrf(v2)
          .setProxyArp(true)
          .build();

  v2.setStaticRoutes(
      ImmutableSortedSet.of(
          StaticRoute.builder()
              .setNextHopInterface(n2i1.getName())
              .setNetwork(Prefix.parse("1.0.0.128/24"))
              .setAdministrativeCost(1)
              .build()));

  Batfish batfish = BatfishTestUtils.getBatfish(configs.build(), _folder);
  batfish.computeDataPlane(batfish.getSnapshot());

  TracerouteQuestion question =
      new TracerouteQuestion(
          c1.getHostname(),
          PacketHeaderConstraints.builder().setDstIp("1.0.0.131").build(),
          false,
          DEFAULT_MAX_TRACES);

  TracerouteAnswerer answerer = new TracerouteAnswerer(question, batfish);
  TableAnswerElement answer = (TableAnswerElement) answerer.answer(batfish.getSnapshot());

  return answer;
}
 
Example 16
Source File: ComparatorTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testNaturalOrder() {
    Comparator<Item> comparator = Comparator.naturalOrder();
    checkComparison(comparator, orderedItems);
    checkComparison(comparator, orderedItemsMatrix);
}
 
Example 17
Source File: InMemoryDataProviderHelpers.java    From flow with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the natural order comparator for the type argument, or the natural
 * order comparator reversed if the given sorting direction is
 * {@link SortDirection#DESCENDING}.
 *
 * @param sortDirection
 *            the sort direction to use
 * @param <V>
 *            the objects to compare
 * @return the natural comparator, with ordering defined by the given sort
 *         direction
 */
public static <V extends Comparable<? super V>> Comparator<V> getNaturalSortComparator(
        SortDirection sortDirection) {
    Comparator<V> comparator = Comparator.naturalOrder();
    if (sortDirection == SortDirection.DESCENDING) {
        comparator = comparator.reversed();
    }
    return comparator;
}
 
Example 18
Source File: CollectionUtils.java    From freecol with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Convenience function to convert an array to a sorted list.
 *
 * @param <T> The array member type.
 * @param array The array to convert.
 * @return A list of the stream contents.
 */
public static <T extends Comparable<? super T>> List<T> sort(T[] array) {
    final Comparator<T> comparator = Comparator.naturalOrder();
    return sort_internal(Arrays.stream(array), comparator);
}
 
Example 19
Source File: DoubleRangeValidator.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a validator for checking that an Double is within a given range.
 *
 * By default the range is inclusive i.e. both minValue and maxValue are
 * valid values. Use {@link #setMinValueIncluded(boolean)} or
 * {@link #setMaxValueIncluded(boolean)} to change it.
 *
 *
 * @param errorMessage
 *            the message to display in case the value does not validate.
 * @param minValue
 *            The minimum value to accept or null for no limit
 * @param maxValue
 *            The maximum value to accept or null for no limit
 */
public DoubleRangeValidator(String errorMessage, Double minValue,
        Double maxValue) {
    super(errorMessage, Comparator.naturalOrder(), minValue, maxValue);
}
 
Example 20
Source File: FSTCompletionBuilder.java    From lucene-solr with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an {@link FSTCompletion} with default options: 10 buckets, exact match
 * promoted to first position and {@link InMemorySorter} with a comparator obtained from
 * {@link Comparator#naturalOrder()}.
 */
public FSTCompletionBuilder() {
  this(DEFAULT_BUCKETS, new InMemorySorter(Comparator.naturalOrder()), Integer.MAX_VALUE);
}