简体   繁体   中英

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<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. Surely there must be a more elegant and less verbose way to do this, in Java I mean?

You can use Entry<String,String> and iterate over it with a for-each loop . You get the Entry object by using Map.entrySet() .

The key and value from an entry can be extracted using Entry.getKey() and 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:

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.

If you're looking to just pretty print the map, this post may be useful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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