如何确定列表是否在 Java 中排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3047051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine if a List is sorted in Java?
提问by Eric Wilson
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.
我想要一个方法,它采用List<T>
whereT
实现Comparable
并返回true
或false
取决于列表是否已排序。
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.
在 Java 中实现它的最佳方法是什么?很明显,泛型和通配符旨在能够轻松处理这些事情,但我正在纠结。
It would also be nice to have an analogous method to check if the list is in reverse order.
有一个类似的方法来检查列表是否按相反顺序排列也很好。
采纳答案by ColinD
Guavaprovides this functionality through its awesome Orderingclass. An Ordering
is a Comparator
++. In this case, if you have a list of some type that implements Comparable
, you could write:
Guava通过其出色的Ordering类提供此功能。AnOrdering
是一个Comparator
++。在这种情况下,如果您有一个实现 的类型的列表Comparable
,您可以编写:
boolean sorted = Ordering.natural().isOrdered(list);
This works for any Iterable
, not just List
, and you can handle null
s easily by specifying whether they should come before or after any other non-null
elements:
这适用于 any Iterable
,而不仅仅是List
,您可以null
通过指定它们是否应该出现在任何其他非null
元素之前或之后来轻松处理s :
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).
Java 8 用户:使用等效的Comparators#isInOrder(Iterable)
代替,因为 Ordering 的其余部分大多已过时(如类文档中所述)。
回答by bragboy
To check whether a list or any data structure for that matter is a task that only takes O(n) time. Just iterate over the list using the Iterator
Interface and run through the data (in your case you already have it ready as a type of Comparable) from start to end and you can find whether its sorted or not easily
检查列表或任何与此相关的数据结构是否只需要 O(n) 时间的任务。只需使用Iterator
接口遍历列表并从头到尾运行数据(在您的情况下,您已经准备好作为可比较的类型),您可以轻松找到它是否已排序
回答by Vivin Paliath
This is an operation that will take O(n) time (worst case). You will need to handle two cases: where the list is sorted in descending order, and where the list is sorted in ascending order.
这是一个需要 O(n) 时间的操作(最坏的情况)。您将需要处理两种情况:列表按降序排序,以及列表按升序排序。
You will need to compare each element with the next element while making sure that the order is preserved.
您需要将每个元素与下一个元素进行比较,同时确保保留顺序。
回答by Daniel
Easy:
简单:
List tmp = new ArrayList(myList);
Collections.sort(tmp);
boolean sorted = tmp.equals(myList);
Or (if elements are comparable):
或者(如果元素具有可比性):
Object prev;
for( Object elem : myList ) {
if( prev != null && prev.compareTo(elem) > 0 ) {
return false;
}
prev = elem;
}
return true;
Or (if elements are not comparable):
或者(如果元素不具有可比性):
Object prev;
for( Object elem : myList ) {
if( prev != null && myComparator.compare(prev,elem) > 0 ) {
return false;
}
prev = elem;
}
return true;
The implementations fail for lists containing null values. You have to add appropriate checks in this case.
对于包含空值的列表,实现失败。在这种情况下,您必须添加适当的检查。
回答by jjnguy
Simply use the iterator to look through the contents of the List<T>
.
只需使用迭代器查看List<T>
.
public static <T extends Comparable> boolean isSorted(List<T> listOfT) {
T previous = null;
for (T t: listOfT) {
if (previous != null && t.compareTo(previous) < 0) return false;
previous = t;
}
return true;
}
回答by Yishai
This is what I would do:
这就是我会做的:
public static <T extends Comparable<? super T>> boolean isSorted(List<T> list) {
if (list.size() != 0) {
ListIterator<T> it = list.listIterator();
for (T item = it.next(); it.hasNext(); item = it.next()) {
if (it.hasPrevious() && it.previous().compareTo(it.next()) > 0) {
return false;
}
}
}
return true;
}
回答by Sean
Here's a generic method that will do the trick:
这是一个可以解决问题的通用方法:
public static <T extends Comparable<? super T>>
boolean isSorted(Iterable<T> iterable) {
Iterator<T> iter = iterable.iterator();
if (!iter.hasNext()) {
return true;
}
T t = iter.next();
while (iter.hasNext()) {
T t2 = iter.next();
if (t.compareTo(t2) > 0) {
return false;
}
t = t2;
}
return true;
}
回答by mikera
One simple implementation on arrays:
数组上的一种简单实现:
public static <T extends Comparable<? super T>> boolean isSorted(T[] a, int start, int end) {
while (start<end) {
if (a[start].compareTo(a[start+1])>0) return false;
start++;
}
return true;
}
Converting for lists:
转换列表:
public static <T extends Comparable<? super T>> boolean isSorted(List<T> a) {
int length=a.size();
if (length<=1) return true;
int i=1;
T previous=a.get(0);
while (i<length) {
T current=a.get(i++);
if (previous.compareTo(current)>0) return false;
previous=current;
}
return true;
}
回答by digitebs
private static <T extends Comparable<? super T>> boolean isSorted(List<T> array){
for (int i = 0; i < array.size()-1; i++) {
if(array.get(i).compareTo(array.get(i+1))> 0){
return false;
}
}
return true;
}
zzzzz not sure guys what you guys are doing but this can be done in simple for loop.
zzzzz 不确定你们在做什么,但这可以在简单的 for 循环中完成。
回答by Wim Deblauwe
If you need it for unit testing, you can use AssertJ. It contains an assertion to check if a List is sorted:
如果你需要它进行单元测试,你可以使用AssertJ。它包含一个断言来检查列表是否已排序:
List<String> someStrings = ...
assertThat(someStrings).isSorted();
There is also an alternative method isSortedAccordingTo
that takes a comparator in case you want to use a custom comparator for the sorting.
isSortedAccordingTo
如果您想使用自定义比较器进行排序,还有一种替代方法可以使用比较器。