Java程序按属性对自定义对象的ArrayList进行排序
要理解此示例,您应该具备以下 Java 编程 主题的知识:
示例:按属性对自定义对象的 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
属性 customProperty
的 CustomObject
类。
我们还添加了一个初始化该属性的构造函数,以及一个返回 customProperty
的 getter 函数 getCustomProperty()
。
在 main()
方法中,我们创建了一个自定义对象的数组列表 list
,并初始化了 5 个对象。
为了按给定属性对列表进行排序,我们使用了 list
的 sort()
方法。sort()
方法接受要排序的列表(最终排序的列表也是相同的)和一个 comparator
。
在我们的例子中,比较器是一个 lambda 表达式,它:
- 从列表中取出两个对象
o1
和o2
, - 使用
compareTo()
方法比较两个对象的customProperty
, - 最终返回正数,如果 o1 的属性大于 o2 的;返回负数,如果 o1 的属性小于 o2 的;如果它们相等,则返回零。
基于此,list
根据属性从最小到最大进行排序,并存储回 list
。