Avinash
Avinash

Reputation: 13257

Sorted Iteration of HashMap Java

I know that HashMap is not sorted but is there any away i can create iterator which returns values in sorted order of key. I can use Sorted versions of the collections but I am looking for a way to do the same with Hash Based map.

Upvotes: 0

Views: 83

Answers (4)

Luke Melaia
Luke Melaia

Reputation: 1468

I'm not sure this is completely possible, at least from a map point of view, although we could create a special hash map the returns keys from a sort order.

The map could extend HashMap and have a variable the contains the sort order and then have a method that returns the keys and values in the sort order.

You could have a static utility method that takes a HashMap and returns an array of Map.Entrys in the sort order.

While the above may work, TreeMap is probably the way to go. It's designed for this task and was written by Josh Blotch so it's bound to be fast at what it does. Reinventing the wheel always takes longer and doesn't work as well.

Note: This depends on the use case. If you only need to use the sorted values once, then the utility method or custom HashMap implementation will be best. If you're planning on using the Map often, then go with a TreeMap.

Upvotes: 0

Boris the Spider
Boris the Spider

Reputation: 61148

With Java 8 this is very simple:

import static java.util.Map.Entry.comparingByKey;

public <K extends Comparable<? super K>, V> Iterator<V> orderedIterator(final Map<K, V> map) {
    return map.entrySet().stream()
            .sorted(comparingByKey())
            .map(Map.Entry::getValue)
            .iterator();
}

Note, this is slow, as the Stream needs to be sorted each time - so iteration becomes O(n lg n) rather than O(n). If you need to do this a lot, you would be better off using a TreeMap - where insertion is O(lg n) (rather than O(1)) but iteration is still O(n).

Upvotes: 0

Eran
Eran

Reputation: 393831

Any such iterator would have to internally sort all the keys of the HashMap in order to be able to iterate over them in sorted order. It would be more efficient to use an already sorted Map implementation.

Upvotes: 3

Henning Luther
Henning Luther

Reputation: 2075

You can use TreeMap since its a sorted map.

Upvotes: 0

Related Questions