Is there a way to start iteration in HashMap from a particular key?
Suppose my map is :
Map map = new HashMap();
map.put(1,"A");
map.put(2,"B");
map.put(3,"B");
map.put(4,"B");
map.put(5,"F");
map.put(6,"Z");
And I want the iteration to start from key 2
.
The regular iteration involves :
public static void printMap(Map map) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
But how to start the iteration from a particular key?
Your question is based on a misunderstanding of what a HashMap
is. In particular, if you started at the key 2
and iterated the remaining entries, there is no guarantee that you would get entries with keys 2
, 3
, 4
, 5
and 6
... in that order, or in any order.
The order of iteration for a HashMap
is undefined, and in most cases unpredictable.
However ... if you used a LinkedHashMap
or a TreeMap
and iterated the entries then you would get them in a defined order:
LinkedHashMap
would (typically) give the entries in insertion orderTreeMap
would give the entries in comparison order of the keys.If you use a LinkedHashMap
, the way to get all entries starting from a given key (in insertion order) is to iterate from the start until you get to the key you want. For example:
public static void printMapFrom(LinkedHashMap<K, V> map, K from) {
boolean found = false;
for (Map<K, V>.Entry entry : map.entrySet()) {
if (!found && !from.equals(entry.getKey())) {
continue;
}
found = true;
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
If you use a TreeMap
, the way to do it is to use tailMap(key)
to get the submap of entries from the key to the end. Then you iterate the submap.
public static void printMapFrom(SortedMap<K, V> map, K from) {
for (Map<K, V>.Entry entry : map.tailMap(from).entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
If you actually don't care that the order of keys in a HashMap
is indeterminate, then you can use the LinkedHashMap
version above with a plain HashMap
or a ConcurrentHashMap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With