Reputation: 7963
I have a Hashmap which has the following
{20/02/2012=20/02/2012, 16/02/2012=16/02/2012}
but this is there as a string(key and value).
Please help me how to sort them based on month and date,
ex : 16/02/2012=16/02/2012,20/02/2012=20/02/2012
i am okay with any way suggested.
Thanks
Upvotes: 0
Views: 81
Reputation: 86
I'm just adding that HashMaps do not retain order, HashMaps use the hash code of the key to place the entry in an array so you'll not be hable to use it with any kind of sort algorithm, you should use in its place a TreeMap or any other Sortable Map implementation
Upvotes: 1
Reputation: 121048
You need to implement a custom comparator and store them in a TreeMap.
For example(using joda-time):
class MyComparator implements Comparator<String> {
@Override
public int compare(String value1, String value2) {
LocalDate date1 = LocalDate.parse(value1, DateTimeFormat.forPattern("dd/MM/yyyy"));
LocalDate date2 = LocalDate.parse(value2, DateTimeFormat.forPattern("dd/MM/yyyy"));
return date1.compareTo(date2);
}
}
TreeMap<String, String> treeMap = new TreeMap<String,String>();
treeMap.put("20/02/2012", "20/02/2012");
treeMap.put("16/02/2012","16/02/2012");
System.out.println(treeMap);
But you should definitely store date in your map and not String, if you can't change this, the use the method above.
Upvotes: 1
Reputation: 200296
As everyone said, using Date
objects in a sorted set will make this much easier. Transform from your string into the date using
new SimpleDateFormat("dd/MM/yyyy").parse(input);
Upvotes: 1