gaurav_376
gaurav_376

Reputation: 59

How to sort map with a date key in reverse order?

I have a hash map in which Date is stored as a key and array list is a value. I want to sort the map in order to display a latest date first and old date last.

E.g we have 4 dates as a key like "01-09-2014","02-09-2014","31-08-2014","30-08-2014";

So output should be "02-09-2014","01-09-2014","31-08-2014", "30-08-2014"

Please help me to solve this issue.

Thanks.

Upvotes: 1

Views: 2767

Answers (3)

Vipul Paralikar
Vipul Paralikar

Reputation: 1568

static void sortMap() throws Exception{
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

    Map<Date, Integer> map = new TreeMap<Date, Integer>(new Comparator<Date>() {
        public int compare(Date date1, Date date2) {
            return date2.compareTo(date1);
        }
    });

    map.put(dateFormat.parse("01-09-2014"), 1);
    map.put(dateFormat.parse("02-09-2014"), 2);
    map.put(dateFormat.parse("31-08-2014"), 3);
    map.put(dateFormat.parse("30-08-2014"), 4);
}

Upvotes: 1

Ankur Singhal
Ankur Singhal

Reputation: 26077

Try with this

public static void main(String[] args) {
        Map<Date, Integer> m = new HashMap<Date, Integer>();

        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

        try {
            m.put(dateFormat.parse("31-05-2011").getTime(), 67);
            m.put(dateFormat.parse("01-06-2011").getTime(), 89);
            m.put(dateFormat.parse("10-06-2011").getTime(), 56);
            m.put(dateFormat.parse("25-05-2011").getTime(), 34);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Map<Date, Integer> m1 = new TreeMap(m, new Comparator<Date>() {
          @Override
          public int compareTo(Date a, Date b) {
            return -a.compare(b);
          }
        });
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

        for (Map.Entry<Date, Integer> entry : m1.entrySet()) {
            System.out.println(df.format(entry.getKey()));
        }
    }

Upvotes: 2

NoDataFound
NoDataFound

Reputation: 11969

Use TreeMap and define an appropriate Comparator that reverse thing (eg: (Date a, Date b) -> -a.compare(b));

Upvotes: 1

Related Questions