示例: 按属性对自定义对象的 ArrayList 进行排序
import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList<Customobject> list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2)-> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } }
输出
A Aa B X Z
在上面的程序中,我们定义了一个带有
String
属性的
CustomObject
类,
customProperty。
我们还添加了一个用于初始化属性的构造函数,以及一个返回
customProperty 的 getter 函数
getCustomProperty()
。
在
main()
方法中,我们创建了一个自定义对象数组列表
list,初始化为 5 个对象。
为了对具有给定属性的列表进行排序,我们使用
list 的
sort()
方法。
sort()
方法接受要排序的列表(最终排序的列表也是如此)和一个
comparator
。
在我们的例子中,比较器是一个 lambda
从列表o1 和o2 中获取两个对象,
使用 compareTo()
方法比较两个对象的 customProperty,
最后,如果 o1 的属性大于 o2,则返回正数,如果 o1 的属性小于 o2,则返回负数,如果相等则返回零。
在此基础上,
list 根据属性从最小到最大排序并存储回
list。