I would like to have a duplicate copy of an entire hashmap that is sorted by key. The hashmap is of type HashMap. Below is what I did.
SortedSet<String> keys = new TreeSet<String>(unsortedap.keySet());
for (String key : keys) {
String value = unsortedMap.get(key);
// I have noticed that here the key values are in order
// How do I copy these ordered values to a hashmap?
}
The values seem to be sorted after using TreeSet, however, I am not sure of what to do now. How can I get these values into a new hashmap?
1 Answer 1
The easiest way is just to put the key-value pairs into a TreeMap. Normally this will be ordered by key in default comparator order. If you need custom ordering you can construct the TreeMap with a custom Comparator which implements your preferred ordering.
Instead of your code, just use:
SortedMap<String, String> sortedMap = new TreeMap<>(unsortedMap);
You can be sure a TreeMap will use the same ordering as a TreeSet if only because a TreeSet uses a TreeMap with null values 'under the hood' for its implementation anyway.
-
I will accept this answer, and do some research on SortedMaps and TreeMaps. Thanks!portfoliobuilder– portfoliobuilder2014年10月29日 21:14:42 +00:00Commented Oct 29, 2014 at 21:14
new TreeMap(unsortedMap)
should work.