Link to home
Start Free TrialLog in
Avatar of rayskelton
rayskelton

asked on

Options for iterating through maps

I am using an iterator to loop through a map to print it’s contents. Are there other simpler options for getting an iterator for a map, other than my below example?
   
Set entries = map.entrySet();
    Iterator iterator = entries.iterator();
    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
      System.out.println("Key:" + entry.getKey() + " : " + entry.getValue());
    }
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Not really. But you could do

System.out.println(iterator.next());
Avatar of aozarov
aozarov

You can print the whole map by doing:
System.out.println(map);

Which will print it in this format "[key1=value1, key2=value2,... ]"
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Are there other simpler options for getting an iterator for a map
objects, Is your suggestion simpler then the one provided rayskelton
Avatar of rayskelton

ASKER

Of the two available options, is there a performance hit for one against the other?

    // get iterator of map through map.entries
    Set entries = map.entrySet();
    Iterator iterator = entries.iterator();
    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
//      dest.write("Key:" + entry.getKey() + " : Message:" + entry.getValue() + "\n");
      dest.write(entry.getKey() + " :: " + entry.getValue() + "\n");
//      dest.write("Message:" + entry.getValue() + "\n");
    }
   
    Iterator iterator1 = map.keySet().iterator();
    dest.write("\nOption 2 for map writing\n");
    while (iterator1.hasNext()) {
      Object key = iterator1.next();
      Object value = map.get(key);
      dest.write(key + " :: " + value + "\n");
    }
 
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I use the following snippet so often that I've made it a macro-template in my JBuilder:

    Map.Entry entry = null;
    for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
      entry = (Map.Entry)iter.next();
      Object key = entry.getKey();
      Object value = entry.getValue();
      // Do whatever with the key and value..
    }
Doubt there would be any significant performance difference, suggest you benchmark if you are dealing with large sets and performance is an issue
thanks for all advice