Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a HashMap starting from a particular key value in Java?

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?

like image 750
parul71625 Avatar asked Feb 05 '23 16:02

parul71625


1 Answers

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.

like image 180
Stephen C Avatar answered Feb 16 '23 04:02

Stephen C