Java Comparator implement to parse String to Date then compare

Description

Java Comparator implement to parse String to Date then compare

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;

class MyComparator implements Comparator<String> {
  private DateFormat format = new SimpleDateFormat("MMyyyy");

  @Override//from www  .ja  va2s  .  c  o m
  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;
  }
}

public class Main {

  public static void main(String[] args) {
    List<String> yearList = new ArrayList<>(25);
    yearList.add("042015");
    yearList.add("wong Value 2");
    yearList.add("052015");
    yearList.add("062015");
    yearList.add("072000");
    yearList.add("082015");
    yearList.add("091998");
    yearList.add("wong Value 3");
    yearList.add("102010");
    yearList.add("112010");
    yearList.add("122010");
    yearList.add("012015");
    yearList.add("022020");
    yearList.add("032015");
    yearList.add("wong Value 1");

    Collections.sort(yearList, new MyComparator());
    System.out.println(yearList);
  }

}



PreviousNext

Related