Reputation: 221
I have a HashMap
which has keys as Date
in String
s and value as an ArrayList
of custom objects. I want to sort this hashmap on the basis of key. How can I do that?
HashMap<String,List<ClassName>> hashmap = new HashMap<String,List<ClassName>>();
When Hashmap
is like this:
{"2015/07/15 : List("Object1","object2","object3")
"2015/07/14 :List("Object4" , "Object5")}
Please suggest.
Upvotes: 1
Views: 99
Reputation: 1905
First thing is you can use TreeMap
when you need a sorted map. However you are storing date value as Strings. Then it become harder to compare each. So i recommend to use java.util.Date
instead of String
. You can use a date formatter when you adding to the map. Use following code.
TreeMap<Date, List> treeMap = new TreeMap<>();
You can specify the Comparator
in the constructor of the TreeMap
. So it's easy to sort up things according to your custom order.
Upvotes: 0
Reputation: 27946
As well as using a sorted map (as others have suggested) you can easily sort the keys when you use them rather than when you insert them.
For example, in Java 8:
treeMap.keySet().stream().sorted().forEach(System.out:println);
A nice thing about this is that it's easy to sort using different comparators without changing the collection.
For example, if you wanted to to sort by the number of items in the list value:
treeMap.keySet().stream().sorted(Comparator.comparingInt(k -> treeMap.get().size()))
This method is good for situations in which you insert and change values in the map often and then occasionally need the keys sorted for a particular operation. You get the performance of a HashMap
but the flexibility to sort however you want on use.
Upvotes: 0
Reputation: 413
You can use TreeMap, if you need the sorted map.
If you don't want to use TreeMap, then get the key and sort it as below.
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
map.put("2015/07/15", list);
map.put("2015/07/17", list1);
map.put("2015/07/16", list1);
ArrayList<String> keyset = new ArrayList<String>(map.keySet());
Collections.sort(keyset);
Upvotes: 0
Reputation: 1658
You can use TreeMap
instead of a HashMap
. The TreeMap
implements the Sorted Map interface.
Upvotes: 3