如何确定List是否以Java排序? [英] How to determine if a List is sorted in Java?

查看:106
本文介绍了如何确定List是否以Java排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个使用 List< T> 的方法,其中 T implements 可比较并返回 true false ,具体取决于列表是否已排序。 / p>

在Java中实现这个最好的方法是什么?很显然,泛型和通配符都可以很容易地处理这些事情,但我现在都陷入了混乱之中。



也有一种类似的方法方法来检查列表是否以相反的顺序排列。

解决方案

Guava 通过其出色的订购课程。 Ordering 比较器 ++。在这种情况下,如果你有一个实现 Comparable 的类型列表,你可以这样写:

  boolean sorted = Ordering.natural()。isOrdered(list); 

这适用于任何 Iterable ,而不仅仅是 List ,您可以轻松处理 null s,方法是指定它们是在任何其他非< c $ c> null 元素:

  Ordering.natural()。nullsLast()。isOrdered清单); 

此外,由于您提到您希望能够检查反向顺序,正常,这将做到:

  Ordering.natural()。reverse()。isOrdered(list); 

Java 8用户:使用等效的比较器#isInOrder(Iterable)代替,因为Ordering的其余部分大多已经过时(正如 documentation )。


I would like a method that takes a List<T> where T implements Comparable and returns true or false depending on whether the list is sorted or not.

What is the best way to implement this in Java? It's obvious that generics and wildcards are meant to be able to handle such things easily, but I'm getting all tangled up.

It would also be nice to have an analogous method to check if the list is in reverse order.

解决方案

Guava provides this functionality through its awesome Ordering class. An Ordering is a Comparator++. In this case, if you have a list of some type that implements Comparable, you could write:

boolean sorted = Ordering.natural().isOrdered(list);

This works for any Iterable, not just List, and you can handle nulls easily by specifying whether they should come before or after any other non-null elements:

Ordering.natural().nullsLast().isOrdered(list);

Also, since you mentioned that you'd like to be able to check for reverse order as well as normal, that would be done as:

Ordering.natural().reverse().isOrdered(list);

Java 8 users: Use the equivalent Comparators#isInOrder(Iterable) instead, since the rest of Ordering is mostly obsolete (as explained in the class documentation).

这篇关于如何确定List是否以Java排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆