像Python字典一样循环Java HashMap?

发布于 2024-09-07 15:09:57 字数 153 浏览 7 评论 0原文

在 Python 中,您可以在字典中包含键、值对,您可以在其中循环遍历它们,如下所示:

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

有没有办法使用 Java HashMap 来做到这一点?

In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:

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

Is there a way to do this with Java HashMaps?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

当爱已成负担 2024-09-14 15:09:57

是的 - 例如:

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

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);
}
稚气少女 2024-09-14 15:09:57

HashMap.entrySet () 将返回类似于字典的键值对 bean。 iteritems()。然后您可以循环遍历它们。

我认为是最接近Python版本的。

The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems(). You can then loop through them.

I think is the closest thing to the Python version.

你好,陌生人 2024-09-14 15:09:57

如答案所示,基本上有两种方法来迭代 Map (在这些示例中假设为 Map)。

  1. 迭代 Map#entrySet()

    for (Entryentry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" +entry.getValue());
    }
    
  2. 迭代Map#keySet(),然后使用 Map#get()获取每个键的值:

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

第二个可能更具可读性,但它会在每次迭代时不必要地调用 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();
        }
    };
}

请注意,可读性应该优先于过早优化,但记住这一点很重要。

As shown in the answers, there are basically two ways to iterate over a Map (let's assume Map<String, String> in those examples).

  1. Iterate over 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:

    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. 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(). The only difference is that in case of the keySet() the next() call of the iterator returns it.next().getKey() instead of it.next().

The AbstractMap#keySet()'s javadoc proves this:

The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator.

The AbstractMap source code also proves this. Here's an extract of keySet() method (somewhere around line 300 in Java 1.6):

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.

酷炫老祖宗 2024-09-14 15:09:57
Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
  System.out.println(i.getKey().toString() + i.getValue().toString);
}

类似的事情...

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

Something like that...

黑色毁心梦 2024-09-14 15:09:57

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

In Java, you can do the same like the following.

    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));
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文