import java.util.Map; import java.util.HashMap; public class MapExample { public static void main(String[] args) { Mapages = new HashMap<>(); ages.put("Alice", 25); ages.put("Bob", 30); ages.put("Charlie", 35); for (Map.Entry entry : ages.entrySet()) { System.out.println(entry.getValue()); // prints the value of each entry } } }
import java.util.Map; import java.util.HashMap; public class MapExample2 { public static void main(String[] args) { MapIn this example, we create a Map of countries and their full names, then check if a value exists in the map. We use a for-each loop with the entrySet() method to iterate through the map and check if any values match the valueToCheck variable. If a match is found, we set a boolean variable to true and exit the loop. Finally, we print a message indicating whether the value exists in the map or not. Package library: java.utilcountries = new HashMap<>(); countries.put("USA", "United States of America"); countries.put("Canada", "Canada"); countries.put("Mexico", "Mexico"); String valueToCheck = "United States of America"; boolean exists = false; for (Map.Entry entry : countries.entrySet()) { if (entry.getValue().equals(valueToCheck)) { exists = true; break; // exit loop if value is found } } if (exists) { System.out.println("The value " + valueToCheck + " exists in the map"); } else { System.out.println("The value " + valueToCheck + " does not exist in the map"); } } }