implementing iterator with iterable to Hashmap - is it possible?

1.4k Views Asked by At

How can I create an Iterator (by implementing iterable) to Hashmap if it doesn't preserve order? my keys should be ordered.. and I want to iterate in descending order

3

There are 3 best solutions below

6
On BEST ANSWER

Use a TreeMap maybe:

The map is sorted according to the natural ordering of its keys

Also, from TreeMap.keySet() documentation:

Returns a Set view of the keys contained in this map. The set's iterator returns the keys in ascending order


Iteration example:

TreeMap<K,V> tree;
// ...
for (final String key : tree.keySet()) {
    final V value = tree.get(key);
}
3
On

It is true that HashMap doesn't preserve insertion order. But, you might use LinkedHashMap of which the Javadoc says (in part)

Hash table and linked list implementation of the Map interface, with predictable iteration order.

0
On

You can copy the entries from the HashMap to a collection that preserves order (like a List) and then sort them based on the keys (in reverse order). You say that you want to sort the keys in descending order, so I assume that the key implements Comparable but since I don't know what the type is of your key, I used type parameters K and V as placeholders.

    Map<K, V> map = new HashMap<>();
    List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Entry<K, V> o1, Entry<K, V> o2) {
            Comparable k1 = (Comparable) o1.getKey();
            Comparable k2 = (Comparable) o2.getKey();
            return -k1.compareTo(k2);
        }
    });