Reputation:
I have a object Contact
public class Contact(){
private Integer idContact
private Date dateDebut;
private Date dateFin;
...............
public Contact(){}
// getters and setters
}
and List<Contact>
contacts
I want to find the Object having the minimum of dateDebut and the Object having maximum of dateFin using Collections.sort(contacts)
or other method.
Upvotes: 0
Views: 149
Reputation: 1481
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
};
Passing comprator to Collections Util, can find object with min debut date at first location of Arraylist
Collections.sort(contactList, DATE_DEBUT_COMPARATOR);
Similarly passing comprator to Collections Util, can find object with max fin date at first location of Arraylist
Collections.sort(contactList, DATE_FIN_COMPARATOR);
Upvotes: 0
Reputation: 973
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());
}
}
Upvotes: 0
Reputation: 77187
Create an inline anonymous Comparator
class and assign it to a constant:
public static final Comparator<Contact> DATE_DEBUT_COMPARATOR = new Comparator<Contact>() {
public int compare(Contact c1, Contact c2) {
return c1.dateDebut.compareTo(c2.dateDebut);
}
}
Upvotes: 5
Reputation: 12006
You can use java.util.Collections.sort(List<T>, Comparator<? super T>)
Upvotes: 0