Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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 139 views
3 answers 105 views
2 answers 66 views
1 answer 66 views
2 answers 126 views
...