Tuesday, January 29, 2013

Sort List of Date

Example to sort a List of Date object using Collections.sort().

package javaapplication1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaApplication1 {
     
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        List<Date> myList = new ArrayList<>();
        myList.add(new Date(2015-1900, 01, 01));
        myList.add(new Date(2013-1900, 01, 01));
        myList.add(new Date(2013-1900, 01, 02));
        myList.add(new Date(2012-1900, 10, 01));
        myList.add(new Date(2012-1900, 11, 01));
        myList.add(new Date(2015-1900, 01, 10));
        
        Collections.sort(myList, new Comparator<Date>(){

            @Override
            public int compare(Date o1, Date o2) {
                return o1.compareTo(o2);
            }
        });
        
        for(int i = 0; i < myList.size(); i++){
            System.out.println(myList.get(i).toString());
        }

    }
    
}

Sort List of Date object
Sort List of Date object


3 comments: