Faria Nazir
Faria Nazir

Reputation: 33

sort Csv using date column (dd/mm/yyyy) java

i have csv as input with 2 columns and want to sort data on basis of date column (dd/mm/yyyy). below code sort the date correctly but i want the related value with that date... output of this code is like

 02/05/2012
 09/11/2012
 10/11/2012

Code:

public static void main(String[] args){
    Date value = null;
    String reader ="";
    String[] input = null ;
    Date date;
    List<Date> dateList = new ArrayList<Date>();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    File file = new File("data.csv");

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        while((reader = br.readLine())!=null){              
            input = reader.split(",");              
             date = df.parse(input[0]);
             dateList.add(date);
        }

        Collections.sort(dateList, new Comparator<Date>() {
             public int compare(Date o1, Date o2){
                 return o1.compareTo(o2);
             }
        });

         for(Date x : dateList){
             System.out.println(df.format(x));               
         }

    } catch (FileNotFoundException fi) {
        fi.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch(ParseException pe){
        pe.printStackTrace();
    }       
}

Upvotes: 1

Views: 1121

Answers (1)

Eric Hughes
Eric Hughes

Reputation: 841

I think it's easiest to use an object to represent each row of your csv. Then, sort those rows. For extra points, have DateRow implement Comparable.

The relevant part inside your try block:

     BufferedReader br = new BufferedReader(new FileReader(file));
     while((reader = br.readLine()) != null) {
         input = reader.split(",");
         DateRow row = new DateRow(
           input,
           df.parse(input[0])
         );
         dateList.add(row);
     }

     Collections.sort(dateList, new Comparator<DateRow>() {
          public int compare(DateRow o1, DateRow o2){
              return o1.getKey().compareTo(o2.getKey());
          }
     });

     for (DateRow row: dateList) {
         System.out.println(row.getData()[0] + "\t" + row.getData()[1]);
     }

The DateRow class (keep it static if you want it to be an internal class of whatever your main method is in):

private static class DateRow {

    private Date key;
    private String[] rowData;

    public DateRow(String[] rowData, Date key) {
      this.rowData = rowData;
      this.key = key;
    }

    public String[] getData() {
      return this.rowData;
    }

    public Date getKey() {
      return this.key;
    }
}

Upvotes: 1

Related Questions