STurchie
0
Q:

java loop through map

for (Map.Entry<String, String> entry : yourHashMap.entrySet()) {
	System.out.println(entry.getKey() + " = " + entry.getValue());
}
8
Map<String, String> map = new HashMap<>();

for(Entry<String, String> entry:map.entrySet()) {
  System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
}
4
for (Map.Entry<String, String> entry : yourHashMap.entrySet()) {
	System.out.println(entry.getKey() + " = " + entry.getValue());
}

map.forEach((k, v) -> {
    System.out.format("key: %s, value: %d%n", k, v);
});
2
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}
1
// Java program for traversing 
// through a hashmap using for-each loop 
  
import java.util.*; 
  
class GfG { 
    public static void main(String[] args) 
    { 
  
        // Consider the hashmap containing 
        // student name and their marks 
        HashMap<String, Integer> hm =  
                     new HashMap<String, Integer>(); 
  
        // Adding mappings to HashMap 
        hm.put("GeeksforGeeks", 54); 
        hm.put("A computer portal", 80); 
        hm.put("For geeks", 82); 
  
        // Printing the HashMap 
        System.out.println("Created hashmap is" + hm); 
  
        // Loop through the hashmap 
        System.out.println("HashMap after adding bonus marks:"); 
  
        // Using for-each loop 
        for (Map.Entry mapElement : hm.entrySet()) { 
            String key = (String)mapElement.getKey(); 
  
            // Add some bonus marks 
            // to all the students and print it 
            int value = ((int)mapElement.getValue() + 10); 
  
            System.out.println(key + " : " + value); 
        } 
    } 
} 
5
// Java program to demonstrate iteration over  
// Map using keySet() and values() methods 
  
import java.util.Map; 
import java.util.HashMap; 
  
class IterationDemo  
{ 
    public static void main(String[] arg) 
    { 
        Map<String,String> gfg = new HashMap<String,String>(); 
      
        // enter name/url pair 
        gfg.put("GFG", "geeksforgeeks.org"); 
        gfg.put("Practice", "practice.geeksforgeeks.org"); 
        gfg.put("Code", "code.geeksforgeeks.org"); 
        gfg.put("Quiz", "quiz.geeksforgeeks.org"); 
          
        // using keySet() for iteration over keys 
        for (String name : gfg.keySet())  
            System.out.println("key: " + name); 
          
        // using values() for iteration over keys 
        for (String url : gfg.values())  
            System.out.println("value: " + url); 
    } 
} 
2
public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}
1

New to Communities?

Join the community