Java Collection How to - Sort string data as date value from List object








Question

We would like to know how to sort string data as date value from List object.

Answer

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/*from  w  w w. j av a  2  s.c  o  m*/
public class Main {

  public static void main(String[] args) {
    List<String> yearList = new ArrayList<>(25);
    yearList.add("042015");
    yearList.add("052015");
    yearList.add("062015");
    yearList.add("072015");
    yearList.add("082015");
    yearList.add("092015");
    yearList.add("102010");
    yearList.add("112010");
    yearList.add("122010");
    yearList.add("012015");
    yearList.add("022015");
    yearList.add("032015");

    Collections.sort(yearList, new Comparator<String>() {
      private DateFormat format = new SimpleDateFormat("MMyyyy");

      @Override
      public int compare(String o1, String o2) {
        int result = 0;
        try {
          Date d1 = format.parse(o1);
          try {
            Date d2 = format.parse(o2);
            result = d1.compareTo(d2);
          } catch (ParseException ex) {
            result = -1;
          }
        } catch (ParseException ex) {
          result = 1;
        }
        return result;
      }
    });
    System.out.println(yearList);
  }

}

The code above generates the following result.