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

51,839 answers

573 users

How to loop through a map in Java

4 Answers

0 votes
import java.util.Map;
 
public class MyClass {
    public static void main(String args[]) {
        Map<Integer, String> map = Map.of(1,"java", 4,"python", 7,"c++", 2,"c");
 
        for (Map.Entry<Integer, String> entry:map.entrySet()) {
            System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
        }
    }
}
 
 
 
 
/*
run:
 
key: 1 value: java
key: 7 value: c++
key: 4 value: python
key: 2 value: c

*/
 

 



answered Apr 4, 2021 by avibootz
0 votes
import java.util.Map;
 
public class MyClass {
    public static void main(String args[]) {
        Map<Integer, String> map = Map.of(1,"java", 4,"python", 7,"c++", 2,"c");
 
        map.forEach((key, value) -> {
            System.out.format("key: %d, value: %s\n", key, value);
        });
    }
}
 
 
 
 
/*
run:
 
key: 4, value: python
key: 7, value: c++
key: 1, value: java
key: 2, value: c

*/

 



answered Apr 4, 2021 by avibootz
0 votes
import java.util.Map;
import java.util.Iterator;

public class MyClass {
    public static void main(String args[]) {
        Map<Integer, String> map = Map.of(1,"java", 4,"python", 7,"c++", 2,"c");
 
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry keyalue = (Map.Entry)it.next();
            System.out.println(keyalue.getKey() + " : " + keyalue.getValue());
        }
    }
}
 
 
 
 
/*
run:
 
2 : c
4 : python
7 : c++
1 : java

*/

 



answered Apr 4, 2021 by avibootz
0 votes
import java.util.Map;
import java.util.Iterator;
 
public class MyClass {
    public static void main(String args[]) {
        Map<Integer, String> map = Map.of(1,"java", 4,"python", 7,"c++", 2,"c", 3,"c++");
  
        for (var entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}
  
  
  
  
/*
run:
  
7 : c++
4 : python
3 : c++
2 : c
1 : java
 
*/

 



answered Nov 8, 2021 by avibootz

Related questions

1 answer 125 views
3 answers 182 views
182 views asked Apr 8, 2021 by avibootz
1 answer 221 views
1 answer 203 views
1 answer 137 views
137 views asked Sep 29, 2019 by avibootz
3 answers 82 views
4 answers 144 views
...