0

I am trying to sort ArrayList w.r.t termDate ArrayList contains firstName,lastName,email,startDate,termDate

Dates can be either empty or null. I have to compare accordingly and put all the null/empty date values at the end.

Collections.sort(usersList, new Comparator<User>() {
                public int compare(User o1, User o2) {
                    if(o1.getTermDate() == null && o2.getTermDate() == null)
                        return 0; //They are both null, both equal
                    if(o1.getTermDate() == null && o2.getTermDate() != null)
                        return -1; // The first is null and the second is not, return the first as lower than the second
                    if(o1.getTermDate() != null && o2.getTermDate() == null)
                        return 1; //The first is not null and the second is, return the first as higher than the second
                    else
                        return o1.getTermDate().compare(o2.getTermDate()); //Return the actual comparison
                }
            });

It is not compiling compare method.

Please guide.

4
  • You need to call compareTo method and not compare. Commented Aug 25, 2015 at 13:36
  • @Tunaki thanks. compareTo is not giving compilation issues. do i need to pass the Collections.sort(..) to ArrayList again or the existing userList will be sorted and I can access it? Commented Aug 25, 2015 at 13:42
  • Collections.sort sorts the list in-place. That means the list given as argument will be sorted after the call to this method. Commented Aug 25, 2015 at 13:48
  • @Tunaki I don't understand why it is not swapping in my case. i have put sysouts to check Term Date: null 2015-08-31 00:00:00.0 Term Date2: -1 null 2015-08-31 00:00:00.0 Term Date: 2015-08-31 00:00:00.0 2015-12-31 00:00:00.0 Term Date4: 2015-08-31 00:00:00.0 2015-12-31 00:00:00.0 Term Date: 2015-12-31 00:00:00.0 null Term Date3: 1 2015-12-31 00:00:00.0 null Term Date: 2015-08-31 00:00:00.0 null Term Date3: 1 2015-08-31 00:00:00.0 null Term Date: null null Term Date1: 0 null null Commented Aug 25, 2015 at 14:41

1 Answer 1

1

You should change return o1.getTermDate().compare(o2.getTermDate()); to return o1.getTermDate().compareTo(o2.getTermDate()); Because the class java.util.Date; has not method called compare.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.