4

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?

parul71625
  • 193
  • 2
  • 4
  • 14
  • 4
    You cannot do that with a HashMap as the iteration order is undefined. You want a TreeMap (or looking at your indexes, maybe just an array or a List). – Thilo Nov 19 '16 at 06:16
  • 1
    Also, in your example you're defining `map` as a [raw type](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). It's best to not do that (see link). Try `Map map = new HashMap()` instead. :) – Gulllie Nov 19 '16 at 06:31
  • Are you using the key (1, 2, 3,...) from the map as some kind of index? Or is it only for the example? – smsnheck Nov 19 '16 at 06:36
  • A HashMap doesn't sort ts data in a particular order. Your question is invalid read the documentation. https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html ? Use a TreeMap as suggested... – firephil Nov 19 '16 at 06:42

2 Answers2

9

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Hey, I know this is from a while ago, but I'm trying to loop through a map with a specific key and the value that's mapped is also another key and so on and so on. Is there a good way to approach this problem? – Spider Jan 09 '20 at 13:44
  • That is nothing to do with this Q&A. Please 1) search the existing Questions for something like your problem, 2) if you cannot find one ask a new one. – Stephen C Jan 09 '20 at 13:50
-1

first define your map Map<Integer, String> map = new LinkedHashMap<Integer,String>(); And then you can use like it

for(Map.Entry<Integer, String> entry: map.entrySet()){
    if(entry.getKey() == 1){
        continue;
    }
    System.out.println(entry.getKey() +" : "+ entry.getValue());
}
jitendra varshney
  • 3,484
  • 1
  • 21
  • 31