Different Ways to Iterate a MapLet's consider the following map for our example. We will Store the student name and marks in the map.Map<String,Integer> studentMarks = new HashMap<String,Integer>(); studentMarks.put("Krishna", 100); studentMarks.put("Peter", 65); studentMarks.put("Mark", 75); studentMarks.put("Sam", 90); studentMarks.put("John", 80);
Using EntrySet
for(Map.Entry<String, Integer> mapEntry:studentMarks.entrySet() ){ System.out.println("Key is " + mapEntry.getKey() + " - Value is " + mapEntry.getValue()); }
Using KeySet
for(String key:studentMarks.keySet() ){ System.out.println("Key is " + key + " - Value is " + studentMarks.get(key) ); }
Using Values
This can be used if you need to iterate through the values.
for(int marks:studentMarks.values()){ System.out.println( marks ); }
Using Iterator
Iterator it = studentMarks.keySet().iterator(); String key; while(it.hasNext()){ key = (String)it.next(); System.out.println("Key is " + key + " - Value is " + studentMarks.get(key)); } |