The best IMO solution would be to use a different data type for the keys - a data type that actually represents a date and that is sorted in a natural date order. Unless otherwise specified, I would use the Joda Time LocalDate type, which represents exactly what you want (just a date, not a date / time, etc.).
If you really want to use string keys, but you can change their format, you can use the yyyy-MM-dd format, which is naturally sorted.
Alternatively, you can pass the Comparator<String> constructor to the TreeMap constructor, where the comparator is the one that parses the two strings when it asks them to compare, and performs a comparison based on the parsing values ββof year / month / day, There is no constructor that uses both its own comparator and the existing map, so you need something like:
Map<String, Integer> modified = new TreeMap<String, Integer>(customComparator); modified.putAll(a);
This approach will be relatively slow if you have a lot of data (due to re-parsing) and it is a little difficult to write - I would use a more suitable data type if possible.
source share