0

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.

2
  • 2
    Create new Comparator class. It has little to do with the Contact class anyway. Commented Sep 19, 2013 at 10:50
  • 1
    Have you tried anything? Commented Sep 19, 2013 at 10:50

4 Answers 4

5

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use java.util.Collections.sort(List<T>, Comparator<? super T>)

1 Comment

Your answer doesn't answer the question.
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());
    }   
}

1 Comment

@CHHIBI AMOR both objects have to be not null cause if they are you may encounter a NullPointerException at runtime.
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
};

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.