I have declared a ArrayList as follows:
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
Each element of oslist contains 5 Hashmaps:
HashMap<String, String> map = new HashMap<String, String>();
map.put(string, string);
map.put(string, string);
map.put(string, string);
map.put(string, string);
map.put(string, string);
One of these is the date in following format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Now I have written this class which sorts this date format. Class and its usage are as follows:
DateObject.java
package com.test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateObject implements Comparable<Object> {
private String date;
private String time;
public DateObject(String dates) {
try {
Date date_for = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
Locale.ENGLISH).parse(dates);
String date_upd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
.format(date_for);
//System.out.println(date_upd);
String[] parts = date_upd.split(" ");
this.date = parts[0];
this.time = parts[1];
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int compareTo(Object o) {
DateFormat formatter;
Date date1 = null;
Date date2 = null;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date1 = (Date) formatter.parse(this.date + " " + this.time);
DateObject other = (DateObject) o;
date2 = (Date) formatter.parse(other.date + " " + other.time);
} catch (ParseException e) {
e.printStackTrace();
}
catch(NullPointerException npe){
System.out.println("Exception thrown "+npe.getMessage()+" date1 is "+date1+" date2 is "+date2);
}
return date2.compareTo(date1);
}
@Override
public String toString(){
return this.date+" "+this.time;
}
}
Test.java
package com.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<DateObject> list = new ArrayList<DateObject>();
;
DateObject d1 = new DateObject("2012-12-05T11:20:19.111Z");
list.add(d1);
d1 = new DateObject("2012-12-05T11:20:19.111Z");
list.add(d1);
d1 = new DateObject("2012-12-04T10:20:19.111Z");
list.add(d1);
d1 = new DateObject("2010-12-07T13:20:19.111Z");
list.add(d1);
d1 = new DateObject("2012-12-05T11:20:19.111Z");
list.add(d1);
Collections.sort(list);
for(DateObject d : list){
System.out.println(d);
}
}
// "yyyy-MM-dd HH:mm:ss
}
My question is how can I use this class to sort my oslist? That is when I sort oslist on the basis of date HashMap my other HashMaps also gets sorted out correspondingly. One thing to note is in oslist date will be stored as String so I can't use sort directly. Thanks.