我有一个对象联系
public class Contact(){
private Integer idContact
private Date dateDebut;
private Date dateFin;
...............
public Contact(){}
// getters and setters
}
和List<Contact>
个联系人
我想找到具有最小dateDebut的Object和使用Collections.sort(contacts)
或其他方法的具有最大dateFin的Object。
答案 0 :(得分:5)
创建内联匿名Comparator
类并将其分配给常量:
public static final Comparator<Contact> DATE_DEBUT_COMPARATOR = new Comparator<Contact>() {
public int compare(Contact c1, Contact c2) {
return c1.dateDebut.compareTo(c2.dateDebut);
}
}
答案 1 :(得分:0)
您可以使用java.util.Collections.sort(List<T>, Comparator<? super T>)
答案 2 :(得分:0)
static Comparator<Contact> DATEDEBUT_COMPARATOR = new Comparator<Contact>() {
@Override
public int compare(Contact first, Contact second) {
assert(first != null);
assert(second != null);
return first.getDateDebut().compareTo(second.getDateDebut());
}
}
static Comparator<Contact> DATEFIN_COMPARATOR = new Comparator<Contact>() {
@Override
public int compare(Contact first, Contact second) {
assert(first != null);
assert(second != null);
return first.getDateFin().compareTo(second.getDateFin());
}
}
答案 3 :(得分:0)
static Comparator<Contact> DATE_DEBUT_COMPARATOR = new Comparator<Contact>() {
@Override
public int compare(Contact first, Contact second) {
return first.getDateDebut().compareTo(second.getDateDebut());
}
// Ascending order of debut date
};
static Comparator<Contact> DATEFIN_COMPARATOR = new Comparator<Contact>() {
@Override
public int compare(Contact first, Contact second) {
return second.getDateFin().compareTo(first.getDateFin());
}
// Descending order of fin date
};
将comprator传递给Collections Util,可以在Arraylist的第一个位置找到最小首次亮相的对象
Collections.sort(contactList, DATE_DEBUT_COMPARATOR);
同样地将comprator传递给Collections Util,可以在Arraylist的第一个位置找到具有最大fin日期的对象
Collections.sort(contactList, DATE_FIN_COMPARATOR);