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
implementing iterator with iterable to Hashmap - is it possible?
1.4k Views Asked by Ohad At
3
There are 3 best solutions below
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
Mapinterface, 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);
}
});
Use a
TreeMapmaybe:Also, from
TreeMap.keySet()documentation:Iteration example: