Java Collections Framework: SortedMap, TreeMap, Hashtable & Properties Explained

📘 Java Learning – Collections Framework (Part 8: SortedMap, TreeMap, Hashtable & Properties) 🗺️🚀 Continuing my Java Collections journey, today I explored Map implementations where ordering, synchronization, and configuration matter. 🔰 SortedMap (I) • Child interface of Map • Stores entries in sorted order of keys (not values) • Sorting can be: • Natural order • Custom order (Comparator) 📌 Key methods: • firstKey(), lastKey() • headMap(), tailMap(), subMap() • comparator() 🔰 TreeMap (C) • Underlying data structure: Red-Black Tree • Entries sorted based on keys • Duplicate keys ❌, duplicate values ✅ • Values can be heterogeneous & non-comparable 📌 Key rules: • Natural sorting → keys must be homogeneous & Comparable • Custom sorting → handled by Comparator 📌 Null behavior: • modern Java, TreeMap does NOT allow null keys • After that → NullPointerException • Null values allowed anytime 📌 Constructors: TreeMap t1 = new TreeMap(); // Natural sorting TreeMap t2 = new TreeMap(Comparator c); // Custom sorting TreeMap t3 = new TreeMap(Map m); TreeMap t4 = new TreeMap(SortedMap m); 🧪 Short Example: TreeMap tm = new TreeMap(); tm.put(3, "Java"); tm.put(1, "Spring"); tm.put(2, "Boot"); tm.put("1", "Program") //ClassCastException tm.put(null, "Demo") // NullPointerException System.out.println(tm); // {1=Spring, 2=Boot, 3=Java} 🔰 Hashtable (C) • Legacy Map class • Fully synchronized → thread-safe • No null key or null value allowed • Slower due to synchronization 📌 Constructors: Hashtable h1 = new Hashtable(); Hashtable h2 = new Hashtable(int capacity); Hashtable h3 = new Hashtable(int capacity, float loadFactor); Hashtable h4 = new Hashtable(Map m); 🧪 Short Example: Hashtable ht = new Hashtable(); ht.put(1, "Java"); ht.put(2, "Spring"); System.out.println(ht); 🔰 Properties (C) • Child class of Hashtable • Used for external configuration • Keys and values must be String • Common use: DB URL, username, password, config values 📌 Advantage: • Change configuration without recompiling code • Only redeployment needed → minimal business impact 📌 Constructor: Properties p = new Properties(); 📌 Important methods: • getProperty() • setProperty() • load(), store() 🧪 Short Example: Properties p = new Properties(); p.setProperty("user", "admin"); p.setProperty("url", "localhost"); System.out.println(p.getProperty("user")); ⭐ Key Takeaways • SortedMap → Sorted keys • TreeMap → Sorted + navigable Map • Hashtable → Thread-safe legacy Map • Properties → Externalized configuration Understanding Maps deeply helps build scalable, configurable, and maintainable Java applications 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #SortedMap #TreeMap #Hashtable #Properties #JavaCollections #LearningJourney

To view or add a comment, sign in

Explore content categories