I have an array of objects and each object has been assigned a date, how can I sort these objects in order of date?

Question

I currently have an array containing objects called 'People'. Each one has a name, day, month, year (of birth). I want to convert these to dates and use the .isAfter() method to compare them and resort them but it does not sort them by date at all. Here is a simpler version of the code

    for (int i = 0; i<peopleArray.size()-1; i++)
    {
        for (int j = 0; j<peopleArray.size()-1; j++)
        {

            LocalDate firstDate = LocalDate.of(Integer.parseInt(peopleArray.get(i).getDOBYear()), 
                                      Integer.parseInt(peopleArray.get(i).getDOBMonth()), 
                                      Integer.parseInt(peopleArray.get(i).getDOBDay()));


            LocalDate secondDate= LocalDate.of(Integer.parseInt(peopleArray.get(j).getDOBYear()), 
                  Integer.parseInt(peopleArray.get(j).getDOBMonth()), 
                  Integer.parseInt(peopleArray.get(j).getDOBDay()));

            if(firstDate.isAfter(secondDate)) 
            {
                Person temp = peopleArray[i];
                peopleArray[i] = peopleArray[i+1];
                peopleArray[i+1] = temp;
             }              
        }
    }

'Person' is the name of the object. Thanks a lot for your help in advance!


Show source
| java   | sorting   | arrays   | datetime   | bubble-sort   2017-01-04 19:01 3 Answers

Answers ( 3 )

  1. 2017-01-04 20:01

    As duffymo suggested, you just have to implement the Comparable interface on People class as follows:

    public class People implements Comparable<People> {
    
        /* Members */
        private String name;
        private int dobDay;
        private int dobMonth;
        private int dobYear;
    
        /* Getter, Setter, Constructor */
    
        /* Get Date Function */
        private Date getDate() {
            return LocalDate.of(this.dobYear, this.dobMonth, this.dobDay);
        }
    
        @Override
        public int compareTo(People people) {
            return this.getDate().isAfter(people.getDate());
        }
    }
    

    And then finally sort the Array as follows:

    Collections.sort(peopleArray);
    
  2. 2017-01-04 20:01

    If your looking for a simpler solution in java, then solution by user2004685 should do.

    Since you've tagged bubble-sort, I'm guessing you need help with the issue in your code.

    Issues:

    1. The loops will never cover the last element in the list. It should run till i/j < size().
    2. The Swap block swaps different elements than the compared elements. You're comparing elements at i and j location but swapping i and i+1
    3. I'm assuming the swap code which access the Array using subscript operator is working on another variable and not the list variable (As Subscript is not applicable for list).
    4. You can enhance the loop by reducing the loop duration. Refer to bubble-sort code provided here for reference.

    Code with Correction:

    for (int i = 0; i<peopleArray.size(); i++)
    {
        for (int j = 0; j<peopleArray.size(); j++)
        {
            LocalDate firstDate = LocalDate.of(Integer.parseInt(peopleArray.get(i).getDOBYear()), 
                                      Integer.parseInt(peopleArray.get(i).getDOBMonth()), 
                                      Integer.parseInt(peopleArray.get(i).getDOBDay()));
    
            LocalDate secondDate= LocalDate.of(Integer.parseInt(peopleArray.get(j).getDOBYear()), 
                  Integer.parseInt(peopleArray.get(j).getDOBMonth()), 
                  Integer.parseInt(peopleArray.get(j).getDOBDay()));
    
            if(firstDate.isAfter(secondDate)) 
            {
                Person temp = peopleArray[i];
                peopleArray[i] = peopleArray[j];
                peopleArray[j] = temp;
             }              
        }
    }
    
  3. 2017-01-04 21:01

    As user2004685 and duffymo said, you need to write a custom compareTo, and the example user2004685 looks correct to me (I don't have a compiler on this computer at the moment).

    One addendum I would suggest, is that you might not want a People class - maybe you just want the array you have now, and you don't always want to sort instances of Person in the way you describe. If so, the thing to do is pass a Comparator to Arrays.sort():

    Arrays.sort(people, new Comparator<Person>() {
        public int compare(Person p1, Person p2) {
            // implement Person.getDOB() in the appropriate way
            return p1.getDOB().compareTo(p2.getDOB());
        }});
    

    Or, if you're using Java8, you can do this even more succinctly with a lambda:

    Arrays.sort(people, (p1,p2) -> p1.getDOB().compareTo(p2.getDOB()));
    
◀ Go back