Sunday, November 10, 2013

How to print / iterate key and values of any map object?


Displaying key, values of any Map object - simplest way :

     We have many ways to display / iterate key, values of a map object. Here I am following advanced for loop and keySet.

Let us take a sample map object..

Map m=new HashMap();
                               m.put("1","one");
                               m.put("2","two");
                               m.put("3","three");
                               m.put("4","four");
                               m.put("5","five");
                               m.put("6","six");

// now we want to display all the keys with their respected values.

//We have a method called keySet() in Map interface. And this HashMap class implements that method.

//This method returns a Set object of  String elements ( we mentioned keys are strings in map object above).

 Set keySet=m.keySet();

//now we can iterate this Set without the help of iterator, because as per java guidelines from here. we can directly iterate set object using for-each loop with out the help of iterator object. So

 for(String key:keySet){
     System.out.println(key+":"+m.get(key)); // will print both key and value, and iterates..till last key.
 }//end for loop

// instead we can also write in a simple step using below line

for(String key:m.keySet()){
   System.out.println(key+":"+m.get(key));
}//end for loop

This is the benefit of for-each loop. Here we use for-each instead of using iterator object, and also we are no need to check for next object existence. 


code snippet:

Test.java
import java.util.*;
public class Test{

public static void main(String nag[]){

Map mp=new HashMap();
mp.put("i","one");
mp.put("2","two");
mp.put("3","three");

System.out.println("iterating....");
Set keySet=mp.keySet();
for(String key:keySet){
                       System.out.println(key+":"+mp.get(key));
}//end loop

            System.out.println("trying new one..:");
         for(String key:mp.keySet()){
                 System.out.println(key+"-"+mp.get(key));
}//end loop

System.out.println("done with new tech..");
}//end main
}//end class




Please send your valuable feedback to :
javaojavablog@googlegroups.com (or) nagarjuna.lingala@gmail.com



No comments:

Post a Comment