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

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

问题描述

我想要一个接受 List 的方法,其中 T 实现 Comparable 并返回 truefalse 取决于列表是否已排序.

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.

在 Java 中实现这一点的最佳方法是什么?很明显,泛型和通配符旨在能够轻松处理这些事情,但我正在纠结.

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 通过它的 比较器 类.

boolean sorted = Comparators.isInOrder(list, comparator);


还有 Ordering 类,尽管这已经过时了.Ordering 是一个 Comparator++.在这种情况下,如果您有一个实现 Comparable 的某种类型的列表,您可以编写:


There's also the Ordering class, though this is mostly obsolete. 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);

这适用于任何 Iterable,而不仅仅是 List,并且您可以通过指定它们应该在之前还是之后轻松处理 null任何其他非null 元素:

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 中排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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