简体   繁体   English

迭代Map中的键和值

[英]Iterating over keys and values in a Map

Sometimes I find myself duplicating code to extract both key and value entries from a Map (when testing/debugging a third-party API, for example). 有时我会发现自己复制代码以从Map中提取键和值条目(例如,在测试/调试第三方API时)。

Map<String, String> someMap;
Set<String> keys = someMap.keySet();
for(int j=0;j<someMap.size();j++){
    String key = (String) keys.toArray()[j];
    System.out.println("key > " + key + "  : value = " + someMap.get(key));
}

I know Groovy has some great abstractions for this (eg Get key in groovy maps ), but I'm constrained to POJ. 我知道Groovy对此有一些很好的抽象(例如, 在groovy地图中获取密钥 ),但我受限于POJ。 Surely there must be a more elegant and less verbose way to do this, in Java I mean? 当然,必须有一种更优雅,更简洁的方式来实现这一点,我的意思是Java?

You can use Entry<String,String> and iterate over it with a for-each loop . 您可以使用Entry<String,String>并使用for-each循环对其进行迭代。 You get the Entry object by using Map.entrySet() . 您可以使用Map.entrySet()获取Entry对象。

The key and value from an entry can be extracted using Entry.getKey() and Entry.getValue() 可以使用Entry.getKey()Entry.getValue()提取条目的键和值

Code example: 代码示例:

Map<String, String> someMap;
for (Entry<String,String> entry : someMap.entrySet()) {
    System.out.println("key > " + entry.getKey()+ "  : value = " + entry.getValue());
}

You can simplify the code by using the for each loop: 您可以使用for each循环来简化代码:

Map<String, String> someMap;
for(String key : someMap.keySet()){
    System.out.println("key > " + key + "  : value = " + someMap.get(key));
}

Or you do this with the entry set. 或者您使用条目集执行此操作。 Amit provided some code for that while I was still editing my answer ;-) 阿米特提供了一些代码,而我还在编辑我的答案;-)

Depending on what you're trying to do, Google collections has a Maps API that provides some helper functions to transform maps etc. 根据您要执行的操作,Google集合中有一个Maps API,它提供了一些帮助函数来转换地图等。

If you're looking to just pretty print the map, this post may be useful 如果您只想打印地图, 这篇文章可能会有用

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

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