Understanding Java Map Collections and Their Core Methods
Map collections store data in key-value pairs, where each entry consists of a unique key mapped to a corresponding value. The structure follows the pattern {key1=value1, key2=value2, ...}, with keys being unique while values can be duplicated. This design makes Map suitable for storing data with one-to-one relationships.
Map implementations derive their behvaior primarily from key handling, with values being secondary. The main implementations include:
HashMap: Provides unordered storage with no duplicate keys and no indexing.
Map<String, Integer> products = new HashMap<>();
products.put("Television", 1000);
products.put("Computer", 10000);
products.put("Television", 1010); // Overwrites previous entry
products.put("Watch", 10);
products.put(null, null);
System.out.println(products); // {null=null, Watch=10, Computer=10000, Television=1010}
LinkedHashMap: Maintains insertion order while preventing duplicate keys.
Map<String, Integer> products = new LinkedHashMap<>();
products.put("Television", 1000);
products.put("Computer", 10000);
products.put("Television", 1010);
products.put("Watch", 10);
products.put(null, null);
System.out.println(products); // {Television=1010, Computer=10000, Watch=10, null=null}
TreeMap: Orders elements by key in natural ascending order without duplicates.
Core Map Operations
All Map implementations share common functionality:
import java.util.HashMap;
import java.util.Map;
public class MapOperations {
public static void main(String[] args) {
Map<String, Integer> data = new HashMap<>();
// Adding elements
data.put("ItemA", 100);
data.put("ItemB", 200);
// 1. Retrieve collection size
System.out.println(data.size());
// 2. Clear all entries
data.clear();
// 3. Check if empty
System.out.println(data.isEmpty());
// 4. Get value by key
data.put("ProductX", 50);
System.out.println(data.get("ProductX"));
// 5. Remove entry by key
System.out.println(data.remove("ProductX"));
// 6. Check key existence
data.put("ProductY", 75);
System.out.println(data.containsKey("ProductY"));
// 7. Check value existence
System.out.println(data.containsValue(75));
// 8. Retrieve all keys
System.out.println(data.keySet());
// 9. Retrieve all values
System.out.println(data.values());
// 10. Merge another map
Map<String, Integer> additionalData = new HashMap<>();
data.putAll(additionalData);
}
}