2

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 (e.g. 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?

Community
  • 1
  • 1
raven
  • 435
  • 6
  • 17

3 Answers3

9

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());
}
amit
  • 175,853
  • 27
  • 231
  • 333
5

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

André Stannek
  • 7,773
  • 31
  • 52
  • This solution is indeed more elegant then the original, but note that for iterating both keys and values - usually it is unadvised to iterate over keys and then get the value using the `get()` method - due to the performance overhead of an extra look up. When you iterate over the `Entry` set, it is expected to perform faster. – amit Jul 18 '12 at 08:31
  • 1
    After reading http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Map.Entry.html, I must agree with Amit. But for implementation purposes, this is my preffered answer. Thanks guys – raven Jul 18 '12 at 08:37
0

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

Community
  • 1
  • 1
qwerty
  • 3,801
  • 2
  • 28
  • 43