[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 239
  • Last Modified:

Sorting a List with Calendar instances

I have List with a set of Java objects - each object has a Calendar instance representing a date - I need to sort the Collection by Date but in some cases the date is null. What is the best way to sort the List ? Currently I am using Apache Commons library but the objects are not getting sorted correctly.

Thanks
0
abuyusuf35
Asked:
abuyusuf35
  • 4
  • 3
1 Solution
 
CEHJCommented:
Please post what you're trying
0
 
CEHJCommented:
If you use a Comparator like the following, the nulls will appear first:
static class NullDateSorter implements Comparator<Date> {
	public int compare(Date d1,Date d2) {
	    int result = 0;
	    if(d1 == null) {
		result = -1;
	    }
	    else if (d2 == null) {
		result = 1;
	    }
	    else {
		result = d1.compareTo(d2);
	    }
	    return result;
	}
    }

Open in new window

0
 
for_yanCommented:
You can write your class implementing Comprator for the objects of your type and within that class you define method int compareTo(yourType t1, yourType t2) and in this method yout get your Calendar instances from t1 and t2, check first if both are nulls you return zero, if t1 gives null and t2 gives not null you return -1, if t2 gives null and t1 not null you return 1 and if both not null you compare dates using d1.compraeTo(d2) method.
When this comparator class is ready you use Collections.sort(list, new MyComparator()) method to sort your list.
I tried this system many times - it works nicely.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
for_yanCommented:
But your objects are not Dates - they just contain dates as a filed; so you should define your comparator fior the tyoe of your objects not for date and you should then within the method - the first thing you do - you getDate() from your object and you compoare Date instances, but the type for which Comporator is defined should be yourType not Date
0
 
CEHJCommented:
btw a Calendar doesn't have null Date instances. You probably mean your Calendar is null
0
 
for_yanCommented:
Actually the great beauty of this way of sorting with comparator is that once you define the method with this signatue  int compare(yourType t1, yourType t2) inside the method you coukd first getDate() from both instances of youType and effectively compare dates; in another case you want to sort by another filed of yourType which is String - so you define another clas extending Comparator and in thAt class method with the same signatur - but inside the method the first operators will be extract those String fileds from youType and then you compare strings. You actually can make it even one claSs extending comparator which would take a flag as parameter of the constrtuctor and depending on the flag you'lleither sort yourType objects by your Date filed or in anotherr case - just changing the flag in the constructor sort yhe same list by string field. That is a very nice way to sort, and uses only standard Java - no additional apache commons jar or anything
0
 
for_yanCommented:

This is illustration of my talk above in the real code and sorting
custom objects (called MyType)  by Calendar field and by name field:

import java.util.*;

public class Miscellaneous {

    public static void main(String[] args) {

        ArrayList<MyType> ar = new ArrayList<MyType>();

        MyType mt = new MyType("Mike");
        mt.setBirthDate(new GregorianCalendar(1985,2,15));
        ar.add(mt);

            mt = new MyType("Nick");
        mt.setBirthDate(new GregorianCalendar(1982,3,1));
                          ar.add(mt);

                 mt = new MyType("Peter");
                         ar.add(mt);

                mt = new MyType("John");
        mt.setBirthDate(new GregorianCalendar(1980,11,20));

                     ar.add(mt);

                            mt = new MyType("Alan");
                          ar.add(mt);



       System.out.println("original order: " + ar);

        Collections.sort(ar, new MyComp(0));


       System.out.println("sorted by date: " + ar);

           Collections.sort(ar, new MyComp(1));

         System.out.println("sorted by name: " + ar);






        
    }
}

class MyType{
    String name;
    Calendar birthDate;

    public MyType(String name) {
        this.name = name;


    }

    public void setBirthDate(Calendar c){
        birthDate = c;
    }

    public Calendar getBirthDate() {
        return birthDate;
    }

    public String getName() {
        return name;
    }

    public String toString(){
        return "(" +name + "  "  + (birthDate == null ? "": birthDate.getTime()) + ")";
    }

}

class MyComp implements Comparator<MyType>{
    int flag;

    public MyComp(int j){
        flag = j;
    }

    public int compare (MyType t1, MyType t2){
        if(flag == 0){
        if(t1.getBirthDate() == null && t2.getBirthDate() == null)return 0;
        if(t1.getBirthDate() == null) return 1;
        if(t2.getBirthDate() == null)return -1;
        return (t1.getBirthDate().compareTo(t2.getBirthDate()));
        } else
        {
            return t1.getName().compareTo(t2.getName());
        }



    }

}

Open in new window


Output:
original order: [(Mike  Fri Mar 15 00:00:00 PST 1985), (Nick  Thu Apr 01 00:00:00 PST 1982), (Peter  ), (John  Sat Dec 20 00:00:00 PST 1980), (Alan  )]
sorted by date: [(John  Sat Dec 20 00:00:00 PST 1980), (Nick  Thu Apr 01 00:00:00 PST 1982), (Mike  Fri Mar 15 00:00:00 PST 1985), (Peter  ), (Alan  )]
sorted by name: [(Alan  ), (John  Sat Dec 20 00:00:00 PST 1980), (Mike  Fri Mar 15 00:00:00 PST 1985), (Nick  Thu Apr 01 00:00:00 PST 1982), (Peter  )]

Open in new window


Objects with null birthdate are coming after all those with dates when sorting by date
in order to rmake them come before the objectse with date
in these two lines 1 and -1 should be swapped, like that:

  if(t1.getBirthDate() == null) return -1;
        if(t2.getBirthDate() == null)return 1;

Let me know if you have any questions.


0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now