原文: https://www.programiz.com/java-programming/examples/sort-custom-objects-property
在此程序中,您将学习按 Java 中给定属性对自定义对象的ArrayList进行排序。
示例:按属性对自定义对象的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());}}}
运行该程序时,输出为:
AAaBXZ
在上面的程序中,我们定义了一个CustomObject类,它带有String属性,即customProperty。
我们还添加了一个初始化属性的构造器,以及一个返回customProperty的获取器函数getCustomProperty()。
在main()方法中,我们创建了以 5 个对象初始化的自定义对象list的ArrayList。
为了对具有给定属性的列表进行排序,我们使用list的sort()方法。sort()方法采用要排序的列表(最终排序的列表也相同)和comparator。
在我们的例子中,比较器是一个 lambda
- 从
o1和o2列表中选取两个对象, - 使用
compareTo()方法比较两个对象的customProperty, - 如果
o1的属性大于o2的属性,最后返回正数;如果o1的属性小于o2的属性,则最后返回负数;如果相等,则返回零。
基于此,基于最小的属性将list排序为最大,并存储回list。
