Reputation: 1631
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
Upvotes: 1
Views: 1444
Reputation: 3943
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);
}
Upvotes: 3
Reputation: 31279
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);
}
});
Upvotes: 0
Reputation: 201477
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.
Upvotes: 1