How to Print HashMap is very common and frequently ask question now a days for testing programming skills in Java.
So,lets try to understand the program given below.
import java.util.HashMap;
import java.util.Set;
public class Test extends Thread{
public static void main(String[] args) {
//Creating HashMap key and value as String.
HashMap<String, String> st = new HashMap<String, String>();
//Putting some key and value in Map
st.put("K1", "V1");
st.put("K2", "V2");
st.put("K3", "V3");
st.put("K4", "V4");
st.put("K5", "V5");
//Now iterate or loop Map by using KeySet method of Map
for(String name: st.keySet()){
String key= name.toString();
//Here we are calling get method of Map class by passing key which is we got from KeySet()
String value= st.get(name).toString();
System.out.println("Key:- "+ key +"value:- "+ value );
}
}
}
note:-
1)KeySet returns set view of the keys contained in map.
2)Changes to map will reflect to set and vice-versa also possible.
Its very simple Program and can be use by beginners who just started learning java and collection.
Any comment or Suggestion is most welcome!
Thanks,
Vikas
No comments:
Post a Comment