Example usage for java.util Comparator naturalOrder

List of usage examples for java.util Comparator naturalOrder

Introduction

In this page you can find the example usage for java.util Comparator naturalOrder.

Prototype

@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() 

Source Link

Document

Returns a comparator that compares Comparable objects in natural order.

Usage

From source file:Main.java

public static void main(String... args) {
    List<String> names3 = null;

    Optional.ofNullable(names3).ifPresent(list -> list.sort(Comparator.naturalOrder()));

    System.out.println(names3);/*from  ww w . j ava  2 s  . co m*/

}

From source file:Main.java

public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(3, 5, 1, 2, 6);
    numbers.sort(Comparator.naturalOrder());
    System.out.println(numbers);//from  w  w  w  .  j  a  v  a 2s . co m

}

From source file:Main.java

/**
 * Exactly the same as {@link Comparator#naturalOrder()}, but can be used to compare objects
 * whose type is unknown. The comparator will throw a {@link ClassCastException} if presented
 * with arguments that aren't mutually {@linkplain Comparable comparable}. 
 *///from ww w  .  java 2s . c o m
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Comparator<Object> naturalOrder() {
    // Use raw type to eliminate the lower bound of Comparable on argument type.
    Comparator ret = Comparator.naturalOrder();
    // This implicitly does an unchecked cast. In this case, it's okay, because we explicitly
    // document this comparator as throwing ClassCastException when given objects that are not
    // Comparable.
    // NB: We do not have our own naturalOrder Comparator, to avoid these type gymnastics and
    // compiler warnings, because it is very convenient for code to test whether a given
    // comparator is a natural ordering:
    //  comparator == Comparator.naturalOrder()
    // We preserve that ability by using the same comparator and doing casts to make javac let us.
    return ret;
}

From source file:Main.java

/**
 * Gets the next or same closest date from the specified days in
 * {@code daysOfWeek List} at specified {@code hour} and {@code min}.
 * //  w ww. j a  v a2  s.  co  m
 * @param daysOfWeek
 *          the days of week
 * @param hour
 *          the hour
 * @param min
 *          the min
 * @return the next or same date from the days of week at specified time
 * @throws IllegalArgumentException
 *           if the {@code daysOfWeek List} is empty.
 */
public static LocalDateTime getNextClosestDateTime(List<DayOfWeek> daysOfWeek, int hour, int min)
        throws IllegalArgumentException {
    if (daysOfWeek.isEmpty()) {
        throw new IllegalArgumentException("daysOfWeek should not be empty.");
    }

    final LocalDateTime dateNow = LocalDateTime.now();
    final LocalDateTime dateNowWithDifferentTime = dateNow.withHour(hour).withMinute(min).withSecond(0);

    // @formatter:off
    return daysOfWeek.stream().map(d -> dateNowWithDifferentTime.with(TemporalAdjusters.nextOrSame(d)))
            .filter(d -> d.isAfter(dateNow)).min(Comparator.naturalOrder())
            .orElse(dateNowWithDifferentTime.with(TemporalAdjusters.next(daysOfWeek.get(0))));
    // @formatter:on
}

From source file:com.netflix.spinnaker.igor.jenkins.JenkinsCache.java

public List<String> getJobNames(String master) {
    List<String> jobs = new ArrayList<>();
    redisClientDelegate.withKeyScan(prefix() + ":" + master + ":*", 1000, page -> jobs
            .addAll(page.getResults().stream().map(JenkinsCache::extractJobName).collect(Collectors.toList())));
    jobs.sort(Comparator.naturalOrder());
    return jobs;/*w  w  w.ja v a  2s .co m*/
}

From source file:com.netflix.spinnaker.igor.build.BuildCache.java

public List<String> getJobNames(String master) {
    List<String> jobs = new ArrayList<>();
    redisClientDelegate.withKeyScan(baseKey() + ":completed:" + master + ":*", 1000, page -> jobs
            .addAll(page.getResults().stream().map(BuildCache::extractJobName).collect(Collectors.toList())));
    jobs.sort(Comparator.naturalOrder());
    return jobs;// w  w  w.  j ava 2s. c o  m
}

From source file:com.netflix.spinnaker.igor.jenkins.JenkinsCache.java

public List<String> getTypeaheadResults(String search) {
    List<String> results = new ArrayList<>();
    redisClientDelegate.withKeyScan(prefix() + ":*:*" + search.toUpperCase() + "*:*", 1000,
            page -> results.addAll(page.getResults().stream().map(JenkinsCache::extractTypeaheadResult)
                    .collect(Collectors.toList())));
    results.sort(Comparator.naturalOrder());
    return results;
}

From source file:com.netflix.spinnaker.igor.build.BuildCache.java

public List<String> getTypeaheadResults(String search) {
    List<String> results = new ArrayList<>();
    redisClientDelegate.withKeyScan(baseKey() + ":*:*:*" + search.toUpperCase() + "*:*", 1000,
            page -> results.addAll(page.getResults().stream().map(BuildCache::extractTypeaheadResult)
                    .collect(Collectors.toList())));
    results.sort(Comparator.naturalOrder());
    return results;
}

From source file:net.orfjackal.retrolambda.test.InterfaceStaticMethodsTest.java

@Test
public void calling_static_methods_of_library_interfaces__new_method_on_old_interface() {
    assumeThat(SystemUtils.JAVA_VERSION_FLOAT, is(lessThan(1.8f)));

    thrown.expect(IncompatibleClassChangeError.class);
    thrown.expectMessage(SystemUtils.isJavaVersionAtLeast(1.6f)
            ? equalTo("Found interface java.util.Comparator, but class was expected")
            : nullValue(String.class)); // on Java 5 there is no message

    // We don't want this call to prevent loading this whole test class,
    // it should only fail when this line is executed
    Comparator.naturalOrder();
}

From source file:com.thinkbiganalytics.metadata.cache.FeedHealthSummaryCache.java

public FeedStatus getUserFeeds(Long time, String feedName) {
    RoleSetExposingSecurityExpressionRoot userContext = feedAclCache.userContext();
    //streamline the summaries as they could have multiple
    Map<String, FeedSummary> latestFeeds = new HashMap<>();

    Comparator<FeedSummary> byRunningStatus = Comparator.comparing(FeedSummary::getRunStatus,
            Comparator.nullsLast(Comparator.naturalOrder()));

    Comparator<FeedSummary> byStartTime = Comparator.comparing(FeedSummary::getStartTime,
            Comparator.nullsLast(Comparator.naturalOrder()));

    getFeedSummaryList(time).stream().filter(
            summary -> (StringUtils.isBlank(feedName) || feedName.equalsIgnoreCase(summary.getFeedName()))
                    && feedAclCache.hasAccess(userContext, summary.getFeedId().toString()))
            .sorted(byRunningStatus.thenComparing(byStartTime)).forEach(f -> {
                String feedId = f.getFeedId().toString();
                if (!latestFeeds.containsKey(feedId)) {
                    latestFeeds.put(feedId, f);
                }/*  ww w .ja  va2s .co  m*/
            });

    //NOTE it could also populate the last job execution time since the above query gets a union of the running jobs along with the latest finished jobs by feed
    List<FeedHealth> feedSummaryHealth = latestFeeds.values().stream()
            .map(f -> FeedModelTransform.feedHealth(f)).collect(Collectors.toList());
    return FeedModelTransform.feedStatus(feedSummaryHealth);
}