-3

How to sort a map on date basis where one element(Value) of the map is date, and I have to sort according to date without removing duplicates.(JDK 1.7)

Map< String, String> hMap=new HashMap<String, String>();

values in the hMap after all the elements being added to it

hMap.put("1","a")
hMap.put("2","b")
hMap.put("3","date");// here I can convert it to date by the help of SimpleDateFormat(yyyyMMdd).
sprinter
  • 27,148
  • 6
  • 47
  • 78
subhashis
  • 4,629
  • 8
  • 37
  • 52
  • I suppose that you want `hMap.put` for those 3 lines. But which is your expected output? Is that `date` a real date? Or is it just a `String` as it is in your example? – ROMANIA_engineer Mar 28 '16 at 10:55
  • You need to know what the format of the date is. and you need to use SImpleDataFormat or DateTimeFormatter. It's not clear what you are having trouble with. – Peter Lawrey Mar 28 '16 at 10:55
  • What's the point of having a map with String and Dates? If you format the date converting it to a String, sort it as a String implementing a Comparator. http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java – RubioRic Mar 28 '16 at 10:55
  • what you mean by "one element is a date"? How values can be sorted, if they are of mixed types? – Alex Salauyou Mar 28 '16 at 11:01
  • Those are existing values in the map and the format is : yyyyMMdd – subhashis Mar 28 '16 at 11:07
  • Hi Sasha that was the problem, you pointed it correctly, If I can set those values in a bean then I can sort it easily but without that any alternative is there. – subhashis Mar 28 '16 at 11:12
  • Possible duplicate... http://stackoverflow.com/questions/6261237/sort-keys-which-are-date-entries-in-a-hashmap – N00b Pr0grammer Mar 28 '16 at 11:18
  • @subhashis so you need to define rule of sorting for mixed types; or first collect only values parceable to `Date`, then sort them. – Alex Salauyou Mar 28 '16 at 12:00

1 Answers1

0

In Java 8 you can sort a map by value using the following:

DateFormat format = ...
hMap.entrySet().stream()
    .sorted(Comparator.comparing(e -> format.parse(e.getValue())))
    ...

Though you would be better off storing as a Map<String,Date> and doing the parsing on input rather than during the sort.

sprinter
  • 27,148
  • 6
  • 47
  • 78