简体   繁体   中英

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.

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.

您可以使用TreeMap,因为它是排序的地图。

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) .

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.Entry s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM