1

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?

asked Oct 29, 2014 at 20:56
5
  • new TreeMap(unsortedMap) should work. Commented Oct 29, 2014 at 20:57
  • It does not seem to have the new order. After I added the code snippet I printed out the hashmap values and they were the same still. The sortedSet is sorted, but I could not cast that to a Hashmap Commented Oct 29, 2014 at 20:57
  • @portfoliobuilder An HashMap doesn't retain a "logical" order such as alphabetical for the key. In fact it has no order. You can use TreeMap instead. Commented Oct 29, 2014 at 21:00
  • Ok, so this I could use an example of. I have not used a TreeMap before (first time hearing about this) Commented Oct 29, 2014 at 21:03
  • Actually you shoul only specify itz type on creation. From then on use either Map or SortedMap. Commented Oct 29, 2014 at 21:10

1 Answer 1

4

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.

answered Oct 29, 2014 at 21:00
1
  • I will accept this answer, and do some research on SortedMaps and TreeMaps. Thanks! Commented Oct 29, 2014 at 21:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.