像Python字典一样循环Java HashMap?

问题描述 投票:0回答:6

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

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

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

java python hashmap equivalent
6个回答
21
投票

是的 - 例如:

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

6
投票

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

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


6
投票

如答案所示,基本上有两种方法可以迭代

Map
(让我们假设这些示例中的
Map<String, String>
)。

  1. 迭代

    Map#entrySet()

    for (Entry<String, String> entry : 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(); } }; }


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


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

类似这样的事情...


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

0
投票
您还可以使用参考方法使用一个衬垫,如下例所示

Map<String, Object> dict=new TreeMap<String, Object>(); dict.put("age", 20); dict.put("height", 1.75); dict.put("country", "India"); dict.put("profession", "developer"); dict.entrySet().stream().forEach(System.out::println);
输出将是

age=20 country=India height=1.75 profession=developer
    
© www.soinside.com 2019 - 2024. All rights reserved.