在此程序中,您將學習按照Java中給定屬性對自定義對象的數(shù)組列表(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類
我們還添加了一個初始化屬性的構(gòu)造函數(shù),以及一個返回customProperty的getter函數(shù)getCustomProperty()
在main()方法中,我們創(chuàng)建了一個自定義對象的數(shù)組列表list,并使用5個對象進行了初始化。
為了使用給定屬性對列表進行排序,我們使用list的sort()方法。sort()方法接受要排序的列表(最終排序的列表也是相同的)和一個比較器
在我們的實例中,比較器是一個lambda表達式
從列表o1和o2中獲取兩個對象
使用compareTo()方法比較兩個對象的customProperty
如果o1的屬性大于o2的屬性,最后返回正數(shù);如果o1的屬性小于o2的屬性,則最后返回負數(shù);如果相等,則返回零。
在此基礎上,列表(list)按最小屬性到最大屬性排序,并存儲回列表(list)