简体   繁体   中英

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?

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 .

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM