This is the my json:
[
{"name": "John Smith","date":"2017-02-02T23:07:09Z","id":"1223234"}
{"name": "John Doe","date":"2015-07-03T21:05:10Z","id":"3242342"},
{"name": "Jane Fan","date":"2016-12-22T13:27:19Z","id":"2123444"}
]
I have already converted the above to hashmap. Now I want to sort the items on the date value.
Are there inbuilt functions that can help me achieve this? Like e.g. sorted in Python
I have already converted the above to hashmap.
I would suggest you don't do that. I suggest you convert it to a List<Person>
where each Person
has a name, date and ID. (If not Person
then some other class.) It makes more sense as a list than a map, because that's really what the JSON shows: a list of objects, each of which has a name, date and ID. I'd personally make the date a java.time.Instant
or something similar, but that's a separate matter.
At that point, all you need to do is either implement a Comparator<Person>
that compares objects by date, or make Person
implement Comparable<Person>
in the same way. Using a separate Comparator<Person>
feels more appropriate in this case, as it seems equally reasonable to sort a List<Person>
by name or ID. Then you just need to call Collections.sort(people, comparator)
and you're done. There are plenty of examples on Stack Overflow to help you sort by a particular property.
The key part is to realize that what you've got isn't naturally a map - it's a list.
See more on this question at Stackoverflow