-1
Collections.sort(foos, new Comparator<Foo>){
public int compare(Foo a, Foo b){
  int dateComparison=a.date.before(b.date);      
   return dateComparison == 0 ?a.amt.compareTo(b.amt) : dateComparison;
    }    
});
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
mindSet
  • 231
  • 2
  • 10
  • So if two dates are `null` what does that mean for your sort? Just sort by the amount? – MadProgrammer Jan 13 '16 at 02:43
  • Conditionon is if two dates are equal then sort on amount.date can contain null value but amt will never at any case.Whn I used the above code I get null pointer exception when it first compare two dates which are null in before() methods – mindSet Jan 13 '16 at 02:52
  • Well, obviously. But are two `null` dates equal? – MadProgrammer Jan 13 '16 at 02:54
  • Yes two null dates are considered equal – mindSet Jan 13 '16 at 03:09
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Tom Jan 13 '16 at 03:14

1 Answers1

0

two null dates are considered equal

So, you simply need to add in a check for two null dates...

Collections.sort(foo, new Comparator<Foo>() {
    public int compare(Foo a, Foo b) {

        int dateComparison = 0;
        if (a.date == null && b.date == null) {
            dateComparison = 0;
        } else if (a.date == null) {
            dateComparison = -1;
        } else if (b.date == null) {
            dateComparison = 1;
        }

        return dateComparison == 0 ? a.amt.compareTo(b.amt) : dateComparison;
    }
});

Now, you will need to adjust the dateComparison for when one of the date values is null based on your needs, but, that's the basic idea

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • thanks@madProgrammer :how can achieve this : if date contain null in an object then that object should not be considered in sorting – mindSet Jan 13 '16 at 04:11
  • @MASHUKAHMED Well, either it needs to be removed from the list or possible sorted to the bottom of the list, you can't "partially" sort a list, it doesn't make sense – MadProgrammer Jan 13 '16 at 04:12