Thursday, 5 July 2012

Sorting List or Lists in Java

Sorting a List> using Collections.sort(List, Comparator)
Example Program:

List> persons;

Collections.sort(persons, new Comparator>()
        {

            @Override
            public int compare(List o1, List o2)
            {
                if ( o1 == null || o2 == null || o1.size() == 0 || o2.size() == 0 )
                    return 0;

                Person item1 = o1.get(0);
                Person item2 = o2.get(0);
                if ( item1 == null )
                {
                    int size = o1.size();
                    for ( int i = 1; i < size; i++ )
                    {
                        item1 = o1.get(i);
                        if ( item1 != null )
                            break;
                    }
                }
                if ( item2 == null )
                {
                    int size = o2.size();
                    for ( int i = 1; i < size; i++ )
                    {
                        item2 = o2.get(i);
                        if ( item2 != null )
                            break;
                    }
                }
                Date d1 = null;
                Date d2 = null;
                if ( item1 != null )
                    d1 = new Date(item1.getTime());
                if ( item2 != null )
                    d2 = new Date(item2.getTime());
                int result = 0;
                if ( d1 != null && d2 != null )
                {
                    if ( d1.before(d2) )
                        result = 1;
                    else if ( d1.after(d2) )
                        result = -1;
                }
                return result;
            }

        });

No comments:

Post a Comment