Java Questions
Java Questions

Reputation: 7963

How to sort hasmap which has string

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

Answers (5)

IvoC
IvoC

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

Eugene
Eugene

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

Marko Topolnik
Marko Topolnik

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

assylias
assylias

Reputation: 328873

  1. Don't store dates as strings in the first place, store them as dates.
  2. You can then use a TreeMap which will automatically sort the dates (keys) for you.
  3. if all your keys are equal to the corresponding values, you can also use a TreeSet

Upvotes: 1

Vikdor
Vikdor

Reputation: 24134

If possible, store your date as yyyy/MM/dd (e.g. 2012/02/16) and use a SortedSet.

Upvotes: 1

Related Questions