-2

Possible Duplicate:
TreeMap sort by value
Map that could be iterated in the order of values

I have a TreeMap of type <String, Date>. I want to sort it by the Dates (most recent first), and I can't use them as the keys as I cannot guarantee that they will be unique. Is there any way to do this?

Community
  • 1
  • 1
user650309
  • 2,639
  • 7
  • 28
  • 47

2 Answers2

5

You can't directly do it, what you can do is to copy the content of the collection into a new one and then sort it, eg:

List<Map.EntrySet<String, Date>> copy = new ArrayList<Map.EntrySet<String, Date>>(treeMap.entrySet());
Collections.sort(copy, new CustomComparator());

class CustomComparator implements Comparator<Map.Entry<String,Date>> {
  public int compareTo(Map.Entry<String,Date> e1, Map.Entry<String,Date> e2) {
    // compare your dates
  }
}

Of course this collection won't be synced with the original one so you must do it again every time the original TreeSet is modified.

Jack
  • 131,802
  • 30
  • 241
  • 343
1

Actually you can have duplicate keys in TreeMap if you really want it

    Map<Date, String> map = new TreeMap<Date, String>(new Comparator<Date>() {
        @Override
        public int compare(Date d1, Date d2) {
            return d1.after(d2) ? 1 : -1;
        }
    });
    Date d1 = new Date(-100000000000L);
    Date d2 = new Date(100000000000L);
    map.put(d2, "s1");
    map.put(d1, "s2");
    map.put(d1, "s3");
    System.out.println(map);

output

{Mon Oct 31 16:13:20 EET 1966=s3, Mon Oct 31 16:13:20 EET 1966=s2, Sat Mar 03 11:46:40 EET 1973=s1}

Note that 2 entries have the same key, and output is sorted by Date as you wanted

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275