The Map Interface
The Map interface in Java represents an object that maps keys to values. It is an ordered collection of key-value pairs, where each key is unique. The main advantage of using a map is that it provides fast access to the value associated with a given key.
The Map interface is part of the java.util package and has several implementations, including HashMap, TreeMap, LinkedHashMap, and ConcurrentHashMap.
The Map interface provides several methods for working with key-value pairs, such as put(), get(), remove(), containsKey(), containsValue(), keySet(), values(), and entrySet().
Here’s an example of using the Map interface to store and retrieve key-value pairs:
Map<String, Integer> map = new HashMap<>();
map.put(“Alice”, 25);
map.put(“Bob”, 30);
map.put(“Charlie”, 35);
System.out.println(map.get(“Bob”)); // Output: 30
map.remove(“Charlie”);
System.out.println(map.containsKey(“Charlie”)); // Output: false
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + “: ” + entry.getValue());
}
// Output:
// Alice: 25
// Bob: 30 In this example, we create a HashMap instance to store key-value pairs. We use the put() method to add key-value pairs to the map, and the get() method to retrieve the value associated with a key. We also use the remove() method to remove a key-value pair from the map, and the containsKey() method to check if a key is present in the map. Finally, we use a for loop to iterate over all the key-value pairs in the map, using the entrySet() method to obtain a set of entries representing the key-value pairs.
Apply for Core Java Developer Certification Now!!
https://www.vskills.in/certification/certified-core-java-developer