Declare and populate a HashMap
HashMap<String, String> myMap = new HashMap<String, String>(); myMap.put("1","First Value"); myMap.put("2","Second Value"); myMap.put("3","Third Value");
I have shown 3 ways of iterating though a HashMap. In the code examples below, I’ll use the HashMap myMap, described above.
Iterating through HashMap : Way 1
for (Map.Entry entry : myMap.entrySet()) { System.out.println("key=" + entry.getKey() + ", val=" + entry.getValue()); }
Iterating through HashMap : Way 3
Iterator it = myMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Integer key = (Integer)entry.getKey(); String val = (String)entry.getValue(); System.out.println("key=" + key + ", val=" + val); }
Iterating through HashMap : Way 2
Iterator iter = myMap.keySet().iterator(); while(iter.hasNext()) { Integer key = (Integer)iter.next(); String val = (String)myMap.get(key); System.out.println("key=" + key + ", val=" + val); }
All of the above examples will result as follows:
key=1, val=First Value key=2, val=Second Value key=3, val=Third Value
This is my first time pay a visit at here and i am actually impressed to read all
at single place.