portfoliobuilder
portfoliobuilder

Reputation: 7856

How to sort HashMap by key order?

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?

Upvotes: 1

Views: 1208

Answers (1)

BarrySW19
BarrySW19

Reputation: 3809

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.

Upvotes: 4

Related Questions