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:
- a
LinkedHashMap
would (typically) give the entries in insertion order
- a
TreeMap
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
.