按对象属性对对象的 ArrayList 进行排序 [英] Sorting ArrayList of Objects by Object attribute
问题描述
我有一个对象数组列表.这些对象有一个属性或数据类型 - 'String'.我需要按该字符串对 Arraylist 进行排序.如何实现这一目标?
I am having an Arraylist of Objects. Those object have an attribute or datatype - 'String'. I need to sort the Arraylist by that string. How to achieve this?
推荐答案
你需要写一个Comparator
并使用 Collections.sort(List
对您的 List
进行排序.
You need to write a Comparator<MyObject>
and use Collections.sort(List<T>, Comparator<? super T>
to sort your List
.
否则,您的 MyObject
也可以 实现 Comparable
,定义一个自然排序来比较你的特定属性,然后使用 Collections.sort(List<;T>
代替.
Or else, your MyObject
can also implements Comparable<MyObject>
, defining a natural ordering that compares on your specific attribute, and then use Collections.sort(List<T>
instead.
根据各种条件对 List
进行排序:
On sorting List
on various criteria:
关于Comparator
和Comparable
- 何时使用 Comparable 与 Comparator
- compare() 和 compareTo() 的区别
- 关于 null 的 Comparable 和 Comparator 契约
- 为什么 Java集合框架提供了两种不同的排序方式?
这篇关于按对象属性对对象的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!