Question

I'm trying to sort a map in java by date key using TreeMap. Here's my code

public static void sort() {

    BufferedReader br;
    String line;
    String[] data;
    Date date ;
    DateFormat df = new SimpleDateFormat("dd-mm-YYY");

    Map<Date,String> map = new TreeMap<Date,String>();

    try {
        br = new BufferedReader(new FileReader(
                "/home/user/Desktop/train/2013-training_set.txt"));

        int i=0;
        while ((line = br.readLine()) != null) {
            ++i;
            data = line.split(":");
            map.put(df.parse(data[1]), line);
        }

        System.out.println(map.size()+" i = "+i);

        Set st = mp.entrySet();
        Iterator it = st.iterator();

        while (it.hasNext()) {

            Map.Entry me = (Map.Entry) it.next();
            System.out.print(me.getKey() + "->:");
            System.out.println(me.getValue());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

The date[1] contains the date in string format and looks like (e.g. 21-3-2013). The problem is that it stores in the TreeMap(mp) only 12 key-value pairs(one for each month) instead of the 103(i) expected. Any ideas ?

Was it helpful?

Solution

See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html.

Use y for year, M for month in year, and d for day in month. Specifically, lowercase m is minute in hour, while uppercase M is month in year.

OTHER TIPS

It looks like the lines

data = line.split(":"); map.put(df.parse(data[1]), line);

Are effectively parsing out only the month. Line.split(":") is going to produce an array split by : . If you have dates formatted in your data file dd:mm:yyyy then the resulting array "data" should be {[dd], [mm], [yyyy]}. So data[1] is going to simply be the month.

I could be wrong, but I suspect this is why you are only getting the 12 key-value pairs; you are parsing only for the month, and any time you get a new month key, you're overwriting the old key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top