xxxxxxxxxx
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
xxxxxxxxxx
// Java Program to Demonstrate
// Working of Map interface
// Importing required classes
import java.util.*;
// Main class
class Main {
// Main driver method
public static void main(String args[])
{
// Creating an empty HashMap
Map<String, Integer> hashmap= new HashMap<String, Integer>();
// Inserting pairs in above Map
// using put() method
hashmap.put("Banana", new Integer(100));
hashmap.put("Orange", new Integer(200));
hashmap.put("Mango", new Integer(300));
hashmap.put("Apple", new Integer(400));
// Traversing through Map using for-each loop
for (Map.Entry<String, Integer> map :
hashmap.entrySet()) {
// Printing keys
System.out.print(map.getKey() + ":");
System.out.println(map.getValue());
}
}
}
xxxxxxxxxx
// Java program to demonstrate
// the working of Map interface
import java.util.*;
class Main {
public static void main(String args[])
{
// Initialization of a Map
// using Generics
Map<Integer, String> hashmap1= new HashMap<Integer, String>();
// Inserting the Elements
hashmap1.put(1, "Apple");
hashmap1.put(2, "Banana");
hashmap1.put(3, "Mango");
for (Map.Entry mapElement : hashmap1.entrySet()) {
int key= (int)mapElement.getKey();
// Finding the value
String value= (String)mapElement.getValue();
System.out.println(key + " : "+ value);
}
}
}
How to iterate through a hashSet
xxxxxxxxxx
// Java program to demonstrate iteration
// over keys and searching for values
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", "www.geeksforgeeks.org");
// looping over keys
for (String name : gfg.keySet())
{
// search for value
String url = gfg.get(name);
System.out.println("Key = " + name + ", Value = " + url);
}
}
}
xxxxxxxxxx
for (auto const& [key, value] : your_map) {
std::cout << key << ':' << value << std::endl;
}