Java 如要取得List中"最大"的物件,可使用Collections.max()方法。
例如List裡面裝的是Employee物件,則取得最大id的物件的方法如下。
public class Employee {
private int id;
private String email;
public Employee(int id, String email) {
this.id = id;
this.email = email
}
// getter and setter ommitted
}
...
...
public static void main(String[] args) {
List list = new ArrayList();
Employee employee3 = new Employee(3, "bill@123.com");
Employee employee1 = new Employee(1, "matt@123.com");
Employee employee2 = new Employee(2, "john@123.com");
list.add(employee3);
list.add(employee1);
list.add(employee2);
// Collections.max()第一個參數為集合物件list,的第二個參數為Comparator介面的實作(匿名類別)
Employee maxIdEmployee = Collections.max(list, new Comparator() {
@Override
public int compare(Employee o1, Employee o2) {
if(o1.getId() > o2.getId()) {
return 1;
} else {
return -1;
}
}
});
System.out.println(maxIdEmployee.getId()); // 3
}
實作的Comparator.compare()方法用來自訂"最大"的規則,例如本範例是以比較id大小,也可改成比較email長度等。
如要對List中的物件進行排序的話可用Collections.sort(),做法相同。
參考:
沒有留言:
張貼留言