如何对集合进行排序?
我有一个通用的Collection
,并且正在尝试弄清楚如何对其中包含的项目进行排序。我尝试了一些方法,但其中任何一个都不起作用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
集合本身没有预定义的顺序,因此您必须将它们转换为
java.util.List。然后您可以使用一种形式的
java.util.Collections.sort
Collections by themselves do not have a predefined order, therefore you must convert them to
a
java.util.List
. Then you can use one form ofjava.util.Collections.sort
Collection
没有顺序,因此想要对其进行排序是没有意义的。您可以对List
实例和数组进行排序,执行此操作的方法是Collections.sort()
和Arrays.sort()
A
Collection
does not have an ordering, so wanting to sort it does not make sense. You can sortList
instances and arrays, and the methods to do that areCollections.sort()
andArrays.sort()
java.util.Collections 提供了两个基本选项:
T 实现了 Comparable
并且您对自然排序感到满意,请使用此选项比较器
,请使用此选项。根据
Collection
的内容,您还可以查看SortedSet
或SortedMap
。You have two basic options provided by
java.util.Collections
:<T extends Comparable<? super T>> void sort(List<T> list)
T implements Comparable
and you're fine with that natural ordering<T> void sort(List<T> list, Comparator<? super T> c)
Comparator
.Depending on what the
Collection
is, you can also look atSortedSet
orSortedMap
.如果您的集合对象是一个列表,我将使用其他答案中建议的排序方法。
但是,如果它不是列表,并且您并不真正关心返回什么类型的 Collection 对象,我认为创建 TreeSet 而不是 List 更快:
If your collections object is a list, I would use the sort method, as proposed in the other answers.
However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:
如果你得到的只有T,你就不能。必须由提供者注入:
或者传入Comparator
You can't if T is all you get. It must be injected by the provider:
or pass in the Comparator
这是一个例子。 (为了方便起见,我使用 Apache 的
CompareToBuilder
类,尽管这可以在不使用它的情况下完成。)如果您正在处理特定的代码并且遇到问题,您可以发布您的伪代码我们可以尽力帮助您!
Here is an example. (I am using
CompareToBuilder
class from Apache for convenience, although this can be done without using it.)If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!
假设您有一个 Person 类型的对象列表,使用 Lambda 表达式,您可以通过执行以下操作对用户的姓氏进行排序:
Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:
我遇到了类似的问题。必须对第三方类(对象)列表进行排序。
ThirdPartyClass 不实现 Java Comparable 接口。我从 mkyong 找到了一个很好的插图关于如何解决这个问题。我必须使用比较器方法来排序。
其中比较器是:
I came across a similar problem. Had to sort a list of 3rd party class (objects).
ThirdPartyClass does not implement the Java Comparable interface. I found an excellent illustration from mkyong on how to approach this problem. I had to use the Comparator approach to sorting.
where the Comparator is: