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

The following examples show how to use java.util.Comparator#naturalOrder() . These examples are extracted from open source projects. 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 Project: Mycat2   File: Column.java    License: 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
@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
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 4
Source Project: jdk8u60   File: SortedOps.java    License: 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 5
@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 6
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 Project: pnc   File: MergeIteratorTest.java    License: 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 8
Source Project: jgitver   File: VersionTest.java    License: 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 9
@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 10
UnionStringsSketchEvaluator() {
  super(Comparator.naturalOrder(), new ArrayOfStringsSerDe());
}
 
Example 11
Source Project: j2objc   File: ComparatorTest.java    License: 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 12
Source Project: batfish   File: TracerouteTest.java    License: 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 13
public void testNaturalOrderComparator() {
    Comparator<String> comp = Comparator.naturalOrder();

    assertComparisons(stringValues, comp, comparisons);
}
 
Example 14
public void testNaturalOrderComparator() {
    Comparator<String> comp = Comparator.naturalOrder();

    assertComparisons(stringValues, comp, comparisons);
}
 
Example 15
Source Project: batfish   File: OspfArea.java    License: 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 16
Source Project: batfish   File: TracerouteTest.java    License: 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 17
/**
 * 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
/**
 * 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 Project: flow   File: DoubleRangeValidator.java    License: 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
/**
 * 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);
}