如何从Java中的特定键值开始迭代HashMap?

par*_*625 3 java iterator hashmap

有没有办法从特定键开始在HashMap中迭代?

假设我的地图是:

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");
Run Code Online (Sandbox Code Playgroud)

我希望迭代从key开始2.

常规迭代涉及:

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());
        }
}
Run Code Online (Sandbox Code Playgroud)

但是如何从特定键开始迭代?

Ste*_*n C 7

你的问题是基于对什么HashMap是误解.特别是,如果你开始在关键2和迭代剩余的条目,也不能保证你会得到的钥匙条目2,3,4,56...的顺序,或以任何顺序.

a的迭代顺序HashMap是未定义的,并且在大多数情况下是不可预测的.

但是......如果您使用了a LinkedHashMap或a TreeMap并且迭代了条目,那么您将按照定义的顺序获取它们:

  • a LinkedHashMap(通常)按插入顺序给出条目
  • a TreeMap将按键的比较顺序给出条目.

如果你使用a LinkedHashMap,从给定键开始(按插入顺序)获取所有条目的方法是从开始迭代,直到你得到你想要的键.例如:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你使用a TreeMap,那么这样做的方法是使用tailMap(key)从密钥到结尾的条目子图.然后迭代子图.

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您实际上并不关心a中的键的顺序HashMap是不确定的,那么您可以使用LinkedHashMap上面的版本使用plain HashMap或a ConcurrentHashMap.