示例:按属性对自定义对象 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
在上面的程序中,我们定义了一个 CustomObject
类,其中包含一个 String
属性 customProperty。
我们还添加了一个 构造函数 来初始化该属性,以及一个返回 customProperty 的 getter 函数 getCustomProperty()
。
在 main()
方法中,我们创建了一个自定义对象列表 list,并初始化了 5 个对象。
为了根据给定属性对 列表 进行排序,我们使用了 list 的 sort() 方法。sort()
方法接受要排序的列表(最终排序后的列表也相同)和一个 comparator
。
在我们的例子中,比较器是一个 lambda 表达式,它
- 从列表中获取两个对象 o1 和 o2,
- 使用
compareTo()
方法比较两个对象的 customProperty, - 并最终返回一个正数(如果 o1 的属性大于 o2 的),一个负数(如果 o1 的属性小于 o2 的),如果相等则返回零。
基于此,list 将根据属性从小到大排序,并重新存储回 list。
注意: 对于 int 类型,我们使用 Comparator.comparingInt(CustomObject::getCustomProperty)
来根据 int 属性对 ArrayList 进行排序。