Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Map Interface → Map in Java

Map Interface

Map in Java

Map Interface in the Java Collections Framework

The Map interface in Java represents collections that store key-value pairs. It extends the Collection interface and provides functionalities specific to maintaining a mapping between unique keys and their associated values.

Characteristics of Map

Key-value pairs: Each element in a map is a key-value pair. Keys must be unique, and values can be duplicated. ⯄ Unordered: Elements (key-value pairs) are not maintained in any specific order. ⯄ Hashing: Most implementations rely on hashing for efficient retrieval based on keys.

Common Implementations of Map

HashMap: Unordered map based on hashing. Offers fast lookups (average constant time) based on keys, but doesn't maintain insertion order. ⯄ TreeMap: Ordered map that maintains key-value pairs in sorted order based on the natural ordering of keys or a custom comparator. Useful when you need to iterate through elements in a specific order based on keys. ⯄ LinkedHashMap: Maintains insertion order of key-value pairs, making it useful when preserving the sequence of elements added to the map is important.

Methods of the Map Interface

put(K key, V value): Associates the specified value with the given key in the map. If the key already exists, the value is replaced with the new value. ⯄ get(Object key): Returns the value associated with the specified key, or null if the key is not found. ⯄ containsKey(Object key): Checks if the map contains the specified key. ⯄ remove(Object key): Removes the key-value pair associated with the specified key from the map. Returns the value that was removed, or null if the key wasn't found. ⯄ isEmpty(): Checks if the map is empty. ⯄ size(): Returns the number of key-value pairs in the map.

Example: Using HashMap

Map example in java using hashmap import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap HashMap<String, Integer> studentGrades = new HashMap<>(); studentGrades.put("Sathish", 90); studentGrades.put("Rizwan", 85); studentGrades.put("Charlie", 78); // Get value for a key Integer aliceGrade = studentGrades.get("Rizwan"); System.out.println("Rizwan's grade: " + aliceGrade); // Check if a key exists if (studentGrades.containsKey("David")) { System.out.println("Available"); } else { System.out.println("Not available"); } } }


Rizwan's grade: 85 David's grade is not present
Explanation : This example demonstrates adding key-value pairs, retrieving a value for a key, and checking for key existence in a HashMap. Remember that the order in which elements are iterated through the map might differ due to the unordered nature of HashMap.