循环Java HashMap像Python Dictionary?

Fed*_*rer 7 python java hashmap equivalent

在Python中,您可以在字典中使用键值对,您可以在其中循环它们,如下所示:

for k,v in d.iteritems():
    print k,v
Run Code Online (Sandbox Code Playgroud)

有没有办法用Java HashMaps做到这一点?

Ric*_*arn 20

是的 - 例如:

Map<String, String> map = new HashMap<String, String>();
// add entries to the map here

for (Map.Entry<String, String> entry : map.entrySet()) {
    String k = entry.getKey();
    String v = entry.getValue();
    System.out.printf("%s %s\n", k, v);
}
Run Code Online (Sandbox Code Playgroud)

  • 将其与Python版本进行比较,让我想起为什么几年前我放弃了Java. (9认同)

小智 6

HashMap.entrySet()将返回类似键值对豆dictionary.iteritems() .然后你可以循环它们.

我认为是最接近Python版本的东西.


Bal*_*usC 6

如答案所示,基本上有两种方法可以迭代a Map(Map<String, String>在这些例子中假设).

  1. 迭代Map#entrySet():

    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 迭代Map#keySet()然后Map#get()用来获取每个键的值:

    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    
    Run Code Online (Sandbox Code Playgroud)

第二个可能更具可读性,但它具有不必要地调用get()每次迭代的性能成本.有人可能认为创建键集迭代器的成本较低,因为它不需要考虑值.但不管你信不信,keySet().iterator() 创建并使用相同的迭代器entrySet().iterator().唯一的区别是,如果迭代器keySet()next()调用返回it.next().getKey()而不是it.next().

这个AbstractMap#keySet()javadoc证明了这一点:

子类的迭代器方法在此映射的entrySet()迭代器上返回一个"包装器对象" .

AbstractMap源代码也证明了这一点.这是keySet()方法的摘录(在Java 1.6中的第300行左右):

public Iterator<K> iterator() {
    return new Iterator<K>() {
        private Iterator<Entry<K,V>> i = entrySet().iterator(); // <-----

        public boolean hasNext() {
            return i.hasNext();
        }

        public K next() {
            return i.next().getKey(); // <-----
        }

        public void remove() {
            i.remove();
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

请注意,可读性应优先于过早优化,但重要的是要记住这一点.