How do you use Map with a simple code example?

A Map is an interface in Java that represents a collection of key-value pairs where each key is unique. It is part of the Java Collections Framework. Common implementations of the Map interface include HashMap, LinkedHashMap, and TreeMap.

The following example demonstrates how to use a HashMap to store and retrieve values using keys:

import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { // Creating a HashMap Map map = new HashMap<>(); // Adding key-value pairs map.put("Apple", 10); map.put("Banana", 20); map.put("Orange", 15); // Retrieving a value int appleCount = map.get("Apple"); System.out.println("Apple count: " + appleCount); // Iterating through the map for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }

Map Java HashMap key-value pairs Collections Framework