How to iterate over map keys and values in Java

2 Answers

0 votes
import java.util.Map;
import java.util.HashMap;
  
public class Program {
    public static void main(String args[]) {
        Map<String, Integer> map = new HashMap<>();
      
        map.put("c", 1);
        map.put("cpp", 2);
        map.put("java", 3);
        map.put("csharp", 4);
      
        map.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));
    }
}
 
  
  
/*
run:
  
Key: cpp Value: 2
Key: csharp Value: 4
Key: c Value: 1
Key: java Value: 3
  
*/

 



answered Feb 1, 2023 by avibootz
edited Apr 18, 2025 by avibootz
0 votes
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;

public class Program {
    public static void main(String args[]) {
        Map<String, Integer> map = new HashMap<>();

        map.put("c", 1);
        map.put("cpp", 2);
        map.put("java", 3);
        map.put("csharp", 4);

        for (Entry<String, Integer> e : map.entrySet()) {
            System.out.println("Key: " + e.getKey() + " Value: " + e.getValue());
        }
    }
}

 
/*
run:
 
Key: cpp Value: 2
Key: csharp Value: 4
Key: c Value: 1
Key: java Value: 3
 
*/

 



answered Apr 18, 2025 by avibootz

Related questions

2 answers 181 views
3 answers 144 views
2 answers 95 views
1 answer 91 views
2 answers 148 views
...