在Python中,您可以在字典中包含键值对,您可以在其中循环遍历它们,如下所示:
for k,v in d.iteritems():
print k,v
有没有办法用 Java HashMap 来做到这一点?
是的 - 例如:
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);
}
HashMap.entrySet()将返回类似于dictionary.iteritems()的键值对bean。然后您可以循环遍历它们。
我认为是最接近Python版本的。
如答案所示,基本上有两种方法可以迭代
Map
(让我们假设这些示例中的 Map<String, String>
)。
Map#entrySet()
:
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
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()
。
的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();
}
};
}
Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
System.out.println(i.getKey().toString() + i.getValue().toString);
}
类似这样的事情...
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));
}
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