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,870 questions

51,793 answers

573 users

How to iterate over a HashMap key and value separately in Java

2 Answers

0 votes
import java.util.HashMap;
import java.util.Map.Entry;

public class MyClass {
    public static void main(String args[]) {
        HashMap<String, String> hm = new HashMap<>();

        hm.put("Java", "ABC");
        hm.put("C++", "AAB");
        hm.put("Python", "ACB");
        hm.put("C", "AAA");
        hm.put("PHP", "ACD");

        for (String key: hm.keySet()) {
            System.out.print(key + " ");
        }
        
        System.out.println();
        
        for (String value: hm.values()) {
            System.out.print(value + " ");
        }
    }
}
 
 
 
 
/*
run:
   
Java C++ C PHP Python 
ABC AAB AAA ACD ACB 
 
*/

 



answered Jan 21, 2022 by avibootz
0 votes
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Iterator;

public class MyClass {
    public static void main(String args[]) {
        HashMap<String, String> hm = new HashMap<>();

        hm.put("Java", "ABC");
        hm.put("C++", "AAB");
        hm.put("Python", "ACB");
        hm.put("C", "AAA");
        hm.put("PHP", "ACD");

        Iterator<String> iterate_key = hm.keySet().iterator();
        while (iterate_key.hasNext()) {
            System.out.print(iterate_key.next() + " ");
        }   

        System.out.println();
        
        Iterator<String> iterate_value = hm.values().iterator();
    
        while (iterate_value.hasNext()) {
            System.out.print(iterate_value.next() + " ");
        }
    }
}
 
 
 
 
/*
run:
   
Java C++ C PHP Python 
ABC AAB AAA ACD ACB 
 
*/

 



answered Jan 21, 2022 by avibootz

Related questions

1 answer 118 views
2 answers 192 views
192 views asked Jan 21, 2022 by avibootz
1 answer 148 views
1 answer 130 views
3 answers 81 views
81 views asked Mar 3, 2025 by avibootz
1 answer 64 views
...