简体   繁体   English

像Python字典一样循环Java HashMap?

[英]Loop Java HashMap like Python Dictionary?

In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below: 在Python中,您可以在字典中具有键/值对,在其中可以循环遍历它们,如下所示:

for k,v in d.iteritems():
    print k,v

Is there a way to do this with Java HashMaps? 有没有办法用Java HashMaps做到这一点?

Yes - for example: 是-例如:

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

The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems() . HashMap.entrySet()将返回键值对的bean,类似于dictionary.iteritems() You can then loop through them. 然后,您可以遍历它们。

I think is the closest thing to the Python version. 我认为这是最接近Python版本的内容。

As shown in the answers, there are basically two ways to iterate over a Map (let's assume Map<String, String> in those examples). 如答案中所示,基本上有两种方法可以遍历Map (在这些示例中Map<String, String>假设Map<String, String> )。

  1. Iterate over Map#entrySet() : 遍历Map#entrySet()

     for (Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } 
  2. Iterate over Map#keySet() and then use Map#get() to get the value for every key: 遍历Map#keySet() ,然后使用Map#get()获取每个键的值:

     for (String key : map.keySet()) { System.out.println(key + "=" + map.get(key)); } 

The second one is maybe more readable, but it has a performance cost of unnecessarily calling get() on every iteration. 第二个可能更具可读性,但是它的性能代价是每次迭代都不必要调用get() One may argument that creating the keyset iterator is less expensive because it doesn't need to take values into account. 有人可能会说,创建键集迭代器的成本较低,因为它不需要考虑值。 But believe it or not, the keySet().iterator() creates and uses the same iterator as entrySet().iterator() . 但不管您相信与否, keySet().iterator()会创建和使用 entrySet().iterator() 相同的迭代entrySet().iterator() The only difference is that in case of the keySet() the next() call of the iterator returns it.next().getKey() instead of it.next() . 唯一的区别是,对于keySet() ,迭代器的next()调用返回it.next().getKey()而不是it.next()

The AbstractMap#keySet() 's javadoc proves this: AbstractMap#keySet()的javadoc证明了这一点:

The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator. 子类的迭代器方法在此映射的entrySet()迭代器上返回一个“包装对象”。

The AbstractMap source code also proves this. AbstractMap源代码也证明了这一点。 Here's an extract of keySet() method (somewhere around line 300 in Java 1.6): 这是keySet()方法的摘录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();
        }
    };
}

Note that readability should be preferred over premature optimization, but it's important to have this in mind. 请注意,可读性应优先于过早的优化,但记住这一点很重要。

Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
  System.out.println(i.getKey().toString() + i.getValue().toString);
}

Something like that... 像这样

In Java, you can do the same like the following. 在Java中,您可以执行以下操作。

    HashMap<String, String> h = new HashMap<String, String>();
    h.put("1","one");
    h.put("2","two");
    h.put("3","three");

    for(String key:h.keySet()){
        System.out.println("Key: "+ key + " Value: " + h.get(key));
    }

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

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