繁体   English   中英

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

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

有没有办法从特定键开始在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");

我希望迭代从关键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());
        }
}

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

您的问题是基于对HashMap的误解。 特别是,如果你开始在关键的2和重述,其余条目,也不能保证你会得到与键条目23456 ...的顺序,或以任何顺序。

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

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

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

如果使用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());
    }
}

如果使用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());
    }
}

如果您实际上并不关心HashMap的键的顺序是不确定的,那么您可以使用上面的LinkedHashMap版本和普通的HashMapConcurrentHashMap

首先定义你的map Map<Integer, String> map = new LinkedHashMap<Integer,String>(); 然后你可以像这样使用它

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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