import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("John", 25); map.put("Mike", 30); map.put("Amy", 35); // Using keySet() method to iterate through the keys for(String key: map.keySet()) { System.out.println(key + " is " + map.get(key) + " years old"); } } }
John is 25 years old Mike is 30 years old Amy is 35 years old
import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("John", 25); map.put("Mike", 30); map.put("Amy", 35); String name = "John"; // Using keySet() method to check if a key exists if(map.keySet().contains(name)) { System.out.println(name + " is " + map.get(name) + " years old"); } } }
John is 25 years oldPackage library: java.util