Java Map Interface & HashMap Explained

📘 Java Learning – Collections Framework (Part 6: Map Interface & HashMap) 🗺️🚀 Continuing my Core Java Collections journey, today I started exploring Map, which stores data as key–value pairs. 🔰 Map Interface • Used to represent data as key–value pairs • Both keys and values are objects • Duplicate keys not allowed, values can be duplicated • Each key–value pair is called an Entry • Map is NOT a child of Collection 📌 Difference • Collection → group of individual objects • Map → group of key–value pairs Example: 101 → "Java" (Entry) 101 = key, Java = value 🔰 Important Map Methods • put(key, value) – adds / replaces value • get(key) • remove(key) • containsKey(), containsValue() • size(), isEmpty(), clear() 🔰 Collection Views of Map • keySet() → Set of keys • values() → Collection of values • entrySet() → Set of entries 🔰 Map.Entry Interface • Each key–value pair is an Entry • Entry exists only inside Map Key methods: • getKey() • getValue() • setValue() 🔰 HashMap (C) • Underlying data structure: Hash Table • No duplicate keys, values can repeat • Insertion order not preserved • One null key allowed, multiple null values allowed • Not synchronized → not thread-safe 🧪 Short Example HashMap m = new HashMap(); m.put(101, "Java"); m.put(102, "Python"); m.put(103, "Programming"); m.put(102, "Spring"); // replaces value System.out.println(m); Set s = m.keySet(); System.out.println(s); // [101, 102, 103] Collection c = m.values(); System.out.println(c); // [Java, Spring, Programming] Set s1 = m.entrySet(); Iterator itr = s1.iterator(); while (itr.hasNext()) {   Map.Entry m1 = (Map.Entry) itr.next();   if (m1.getKey().equals(102)) {     m1.setValue("Python");   } } System.out.println(m); // {101=Java, 102=Python, 103=Programming} ⭐ Key Takeaway • Map is for relationships (key → value) • HashMap is fast but not thread-safe Building strong Java fundamentals, one Map at a time ☕💻 #Java #CoreJava #CollectionsFramework #Map #HashMap #JavaCollections #LearningJourney

To view or add a comment, sign in

Explore content categories