📘 Java Learning – Collections Framework Part 7: HashMap Variants (Hashtable, LinkedHashMap, IdentityHashMap, WeakHashMap) 🚀 Continuing my Java Collections series, this post focuses on different Map implementations and their practical behavior. 🔰 HashMap vs Hashtable HashMap • Not synchronized • Faster performance • Allows one null key and multiple null values Hashtable • Fully synchronized (thread-safe) • Slower due to thread waiting • Null key & null values not allowed 🧪 Example HashMap m = new HashMap(); m.put(1, "Java"); m.put(null, "Spring"); // allowed System.out.println(m); Hashtable ht = new Hashtable(); ht.put(1, "Java"); // ht.put(null, "Spring"); // NullPointerException 📌 Synchronized HashMap Map m = Collections.synchronizedMap(new HashMap()); 🔰 LinkedHashMap • Child class of HashMap • Maintains insertion order • Underlying structure: HashTable + LinkedList 🧪 Example LinkedHashMap lm = new LinkedHashMap(); lm.put(1, "Java"); lm.put(2, "Spring"); lm.put(3, "Boot"); System.out.println(lm); // Output: {1=Java, 2=Spring, 3=Boot} 📌 Use case Cache-like applications where: • Duplicates are not allowed • Insertion order must be preserved 🔰 IdentityHashMap • Same as HashMap except key comparison • Uses == instead of equals() • Comparison is reference-based 🧪 Example IdentityHashMap im = new IdentityHashMap(); Integer i1 = new Integer(10); Integer i2 = new Integer(10); im.put(i1, "Java"); im.put(i2, "Spring"); System.out.println(im); // Both entries stored (different references) 📌 Note: • HashMap → uses equals() • IdentityHashMap → uses == 🔰 WeakHashMap • Same as HashMap except GC behavior • Keys eligible for Garbage Collection • Entry removed if key has no external reference 🧪 Example WeakHashMap wm = new WeakHashMap(); Integer i = new Integer(10); wm.put(i, "Java"); i = null; System.gc(); System.out.println(wm); // Entry may be removed after GC runs 📌 Note: • HashMap → Map dominates GC • WeakHashMap → GC dominates Map ⭐ Key Takeaways • Hashtable → thread-safe but slow • LinkedHashMap → ordered Map • IdentityHashMap → reference-based keys • WeakHashMap → GC-friendly keys Choosing the right Map implementation is a design decision, not just an API choice 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #HashMap #LinkedHashMap #IdentityHashMap #WeakHashMap #Hashtable #JavaCollections #LearningJourney
Java Collections Framework: HashMap Variants Explained
More Relevant Posts
-
📘 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
-
🚀 Day 31 | Core Java Learning Journey 📌 Topic: HashMap & Map Implementations (Internal Working + Concepts) Today, I deep-dived into how HashMap actually works internally along with LinkedHashMap, TreeMap, and Hashtable. This helped me understand not just usage, but the logic behind performance. 🔹 What is HashMap? ✔ HashMap is a class that implements Map interface ✔ Stores data in key-value pairs ✔ Allows one null key and multiple null values ✔ Not synchronized (not thread-safe) 🔹 Internal Working of HashMap ✔ Default initial capacity = 16 (bucket size) ✔ Data is stored in buckets (array of nodes) ✔ Each key’s hashCode() is used to find bucket index ✔ Formula: index = hash(key) & (n - 1) ✔ If two keys have same bucket index → Collision occurs 👉 Collision Handling: • Uses Linked List (before Java 8) • Uses Linked List + Balanced Tree (after Java 8) • If bucket size > 8 → converts into Red-Black Tree • If reduced → converts back to Linked List ✔ Load Factor = 0.75 (default) ✔ When threshold exceeds → resizing (rehashing) happens 🔹 Important Concepts ✔ Bucket → Each index of internal array ✔ Hashing → Converting key into integer hash ✔ Collision → Multiple keys at same index ✔ Rehashing → Increasing size & redistributing data 🔹 LinkedHashMap ✔ Extends HashMap ✔ Maintains insertion order ✔ Uses doubly linked list internally ✔ Slightly slower than HashMap 🔹 TreeMap ✔ Implements NavigableMap ✔ Stores keys in sorted order (natural/custom comparator) ✔ Uses Red-Black Tree internally ✔ Does NOT allow null key 🔹 Hashtable ✔ Legacy class (introduced before collections framework) ✔ Thread-safe (synchronized) ✔ Does NOT allow null key or value ✔ Slower due to synchronization 🔹 Key Differences ✔ HashMap → Fastest, no ordering ✔ LinkedHashMap → Maintains insertion order ✔ TreeMap → Sorted data ✔ Hashtable → Thread-safe but slower 📌 When to Use What? ✅ Use HashMap → Best performance, general use ✅ Use LinkedHashMap → Order matters ✅ Use TreeMap → Sorted output required ✅ Use Hashtable → Thread-safe (but prefer ConcurrentHashMap in modern Java) 💡 Key Takeaway: Understanding internal working of HashMap (buckets, hashing, collisions, rehashing) helps write optimized and scalable code instead of just using it blindly. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #HashMap #LinkedHashMap #TreeMap #Hashtable #JavaCollections #Programming #LearningJourney
To view or add a comment, sign in
-
-
Day 6 – TreeSet in Java Collections | Sorted Set | Custom Sorting (Backend Developer Learning Series) Today I revised TreeSet, one of the important implementations of the Set interface in Java Collection Framework. TreeSet is very useful when we need unique elements along with automatic sorting. 📌 What is TreeSet? TreeSet is a class that implements the NavigableSet interface, which extends SortedSet. It is available in the java.util package. TreeSet was introduced in JDK 1.2 as part of the Collection Framework. ⚙ Underlying Data Structure TreeSet internally uses a Red-Black Tree. Because of this, elements are stored in sorted order. Sorting happens using: Natural sorting (Comparable) Custom sorting (Comparator) ✨ Characteristics of TreeSet ✔ Duplicate values are NOT allowed ✔ Elements are stored in sorted order ✔ Insertion order is NOT maintained ✔ Null values are NOT allowed ✔ Heterogeneous objects are not allowed ✔ It is not index based 📊 Example Program – TreeSet with Integer import java.util.*; public class TreeSetExample { public static void main(String[] args) { TreeSet<Integer> t = new TreeSet<>(); t.add(10); t.add(50); t.add(9); t.add(12); t.add(45); t.add(55); t.add(1); System.out.println(t); } } TreeSet with Custom Object If we want to store custom objects in TreeSet, the object must implement: Comparable interface or use Comparator Example fields: ticketNo price source destination **Sorting can be done based on price, ticket number, or destination. Practice Java Programs (Based on TreeSet) 1️⃣ Add integer objects to TreeSet and display sorted output. 2️⃣ Write a program to store String values in TreeSet and display them in sorted order. 3️⃣ Write a program to store Integer values in TreeSet in descending order. 4️⃣ Write a program to remove duplicates using TreeSet. 5️⃣ Create a Ticket class and store objects in TreeSet sorted by price. 6️⃣ Write a program to check if an element exists in TreeSet using contain(); 7️⃣ Write a program to display first and last element of TreeSet. 8️⃣ Write a program to remove the highest element from TreeSet. Method: pollLast() 9️⃣ Write a program to store custom objects in TreeSet using Comparator. 🔟 Write a program to convert ArrayList → TreeSet to remove duplicates and sort data. #Java #BackendDeveloper #JavaCollections #TreeSet #Set #SpringBoot #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
📘 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
-
📘 Java Learning – Collections Framework (Final Part: Collections Class & Arrays Class) 🚀🎯 Wrapping up my Java Collections journey with two powerful utility classes from java.util package: 👉 Collections class 👉 Arrays class These classes provide utility methods for sorting, searching, reversing, and converting data structures efficiently. 🔰 Collections Class A utility class that provides methods for Collection implemented classes. 📌 Sorting a List Collections.sort(List l); // Natural sorting Collections.sort(List l, Comparator c); // Custom sorting ✔ Elements must be homogeneous & Comparable (for natural sorting) ✔ Null elements not allowed (NullPointerException) 📌 Searching in a List Collections.binarySearch(List l, Object obj); Collections.binarySearch(List l, Object key, Comparator c); ⚠ Important Rules: • List must be sorted before searching • Uses Binary Search algorithm • Successful search → returns index • Unsuccessful search → returns insertion point • Must use same Comparator used for sorting 📌 Reversing a List Collections.reverse(List l); // Reverses list Collections.reverseOrder(); // Returns Comparator (descending) ✔ reverse() → works on List ✔ reverseOrder() → returns Comparator 🔰 Arrays Class Utility class for array operations (primitive & object arrays). 📌 Sorting Arrays Arrays.sort(int[] arr); // Primitive (natural order) Arrays.sort(Object[] arr); // Natural order Arrays.sort(Object[] arr, Comparator c); // Custom sorting ✔ Primitive arrays → only natural sorting ✔ Object arrays → natural or custom sorting 📌 Searching in Arrays Arrays.binarySearch(int[] arr, key); Arrays.binarySearch(Object[] arr, key); Arrays.binarySearch(Object[] arr, key, Comparator c); ✔ Same rules as Collections.binarySearch() 🔰 Converting Array to List List list = Arrays.asList(Object[] arr); ⚠ Important: • Creates a List view, not independent list • Changes in list reflect in array & vice versa • Cannot change size (add/remove → UnsupportedOperationException) • Replacement allowed but type must match (else ArrayStoreException) 🧪 Combined Example Integer[] arr = {30, 10, 20}; Arrays.sort(arr); // Sorting array System.out.println(Arrays.toString(arr)); // [10, 20, 30] int index = Arrays.binarySearch(arr, 20); System.out.println(index); // 1 List list = Arrays.asList(arr); Collections.reverse(list); System.out.println(list); // [30, 20, 10] ⭐ Final Takeaways • Collections → Utility methods for List • Arrays → Utility methods for Arrays • Always sort before binarySearch • asList() creates a fixed-size list view This completes my Java Collections Framework journey 🎯 Understanding these utilities makes data handling more efficient and interview-ready 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #CollectionsClass #ArraysClass #JavaCollections #LearningJourney
To view or add a comment, sign in
-
🚀 Day 33 | Core Java Learning Journey 📌 Topic: File Handling in Java Today, I explored File Handling in Java — how applications store and retrieve data from files. This is a very important concept for building real-world applications where data persistence is required. 🔹 What is File Handling? ✔ File Handling is used to store data permanently in files ✔ It allows Java applications to read, write, and modify files ✔ Available through the java.io package 🔹 Why We Use File Handling? ✔ To store data permanently (even after program ends) ✔ To read existing data from files ✔ To build data-driven applications ✔ Used in logging, reports, configs, etc. 🔹 Important Classes in java.io.* ✔ File → Represents file or directory ✔ FileWriter → Writes data to file (character stream) ✔ FileReader → Reads data from file ✔ BufferedWriter → Efficient writing (faster) ✔ BufferedReader → Efficient reading (line by line) ✔ FileInputStream → Reads binary data ✔ FileOutputStream → Writes binary data ✔ InputStreamReader → Converts byte stream → character stream 🔹 Steps to Work with Files ✔ Step 1: Import package • import java.io.*; ✔ Step 2: Create File Object • File file = new File("test.txt"); ✔ Step 3: Write Data • FileWriter fw = new FileWriter(file); • fw.write("Hello Students"); ✔ Step 4: Read Data • FileReader fr = new FileReader(file); ✔ Step 5: Close Resources • Always close streams → fw.close(), fr.close() 🔹 Important Methods ✔ createNewFile() → Creates new file ✔ exists() → Checks file existence ✔ delete() → Deletes file ✔ write() → Writes data ✔ read() → Reads single character ✔ readLine() → Reads line (BufferedReader) ✔ flush() → Clears buffer and forces write ✔ close() → Closes stream 🔹 Key Concepts ✔ Buffered Streams → Faster performance ⚡ ✔ Character Streams → FileReader, FileWriter ✔ Byte Streams → FileInputStream, FileOutputStream ✔ Exception Handling → Must handle IOException ✔ Try-with-resources → Recommended (auto close) ✅ 🔹 Example (Best Practice) ✔ Using try-with-resources: • try (FileWriter fw = new FileWriter("test.txt")) { fw.write("Hello Students"); } 🔹 Store & Fetch Data ✔ Store → Using FileWriter / BufferedWriter ✔ Fetch → Using FileReader / BufferedReader ✔ Supports both text and binary data 📌 When to Use File Handling? ✅ When saving user data locally ✅ When working with logs or reports ✅ When database is not required ✅ When handling configuration files 💡 Key Takeaway: File Handling is essential for data persistence in Java. Understanding streams and proper resource management helps build efficient and reliable applications. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #FileHandling #JavaIO #Programming #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 12 – Strings in Java | My Learning Journey Today I learned about one of the most important concepts in Java: Strings. Strings are widely used in almost every Java application because they help us store and manipulate textual data. 🔹 What is a String? A String is a sequence of characters such as letters, numbers, or symbols. In Java, a String is not a primitive data type; it is an object of the String class. Example: String name = "Java"; 🔹Types of Strings in Java There are mainly two types of strings: 1️⃣ Immutable Strings Once created, the value of the string cannot be changed. Any modification will create a new string object. Example: String s = "Hello"; s.concat(" World"); The original string "Hello" remains unchanged. 2️⃣ Mutable Strings Mutable strings allow modification of the content without creating a new object. Examples include: StringBuffer StringBuilder 🔹 Different Ways to Create Immutable Strings 1️⃣ Using String Literal String s1 = "Java"; 2️⃣ Using the new Keyword String s2 = new String("Java"); 3️⃣ Using Character Array char ch[] = {'J','a','v','a'}; String s3 = new String(ch); 🔹 Different Ways to Compare Strings 1️⃣ Using == Operator Compares memory references. String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); 2️⃣ Using equals() Method Compares actual string values. String s1 = "Java"; String s2 = "Java"; System.out.println(s1.equals(s2)); 3️⃣ Using compareTo() Method Used for lexicographical comparison of strings. 🔹 Where Are Strings Created in Memory? In Java, strings are stored in two memory areas: 📌 String Pool (inside Heap Memory) Stores string literals. If the same literal already exists, Java reuses the existing object. 📌 Heap Memory Strings created using the new keyword are stored in the heap memory. Example: String s1 = "Java"; // Stored in String Pool String s2 = new String("Java"); // Stored in Heap Understanding strings helps in writing efficient and optimized Java programs, especially when dealing with text processing, user input, and data manipulation. Learning about string creation, comparison, immutability, and memory management gave me a deeper understanding of how Java internally manages text data. #Java #StringsInJava #LearningJourney #Programming #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
📘 Java Learning – Multithreading (Part 3: Runnable Interface, Thread Names & Priorities) 🚀🎯 Continuing my learning journey into Java Multithreading. In this post, I explored how to define threads using the Runnable interface, along with concepts like thread names and priorities. 🔰 Defining a Thread using Runnable Interface A thread can also be defined by implementing the Runnable interface, which is present in the java.lang package and contains only one method: • run() 📌 Two Approaches to Define a Thread 1️⃣ Extending Thread class 2️⃣ Implementing Runnable interface 📌 Example – Runnable Implementation class MyRunnable implements Runnable { public void run() { System.out.println("Child Thread"); } public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); System.out.println("Main Thread"); } } ✔ Output may appear in mixed order because execution depends on the Thread Scheduler. 🔰 Best Approach to Define a Thread Between the two approaches, implementing Runnable is recommended. Reason: • If a class extends Thread, it cannot extend any other class • If a class implements Runnable, it can still extend another class ✔ This provides better flexibility in design. 🔰 Common Thread Constructors Some commonly used constructors of the Thread class: Thread() Thread(Runnable r) Thread(String name) Thread(Runnable r, String name) Thread(ThreadGroup g, String name) Thread(ThreadGroup g, Runnable r) Thread(ThreadGroup g, Runnable r, String name) Thread(ThreadGroup g, Runnable r, String name, long stackSize) 🔰 Getting and Setting Thread Name Every thread in Java has a name (default or programmer-defined). Methods used: • getName() • setName(String name) Example: System.out.println(Thread.currentThread().getName()); // main Thread.currentThread().setName("first thread"); System.out.println(Thread.currentThread().getName()); To get the current executing thread reference: Thread.currentThread() 🔰 Thread Priority Every thread has a priority ranging from 1 (lowest) to 10 (highest). Standard constants: • Thread.MIN_PRIORITY • Thread.NORM_PRIORITY • Thread.MAX_PRIORITY If two threads have the same priority, the execution order depends on the Thread Scheduler. 🔰 Default Priority • Default priority of main thread → 5 • Child threads inherit priority from the parent thread Methods used: • getPriority() • setPriority(int p) Example: t.setPriority(5); t.setPriority(10); t.setPriority(100); // IllegalArgumentException ⭐ Key Takeaways • Threads can be created using the Runnable interface • Implementing Runnable offers better design flexibility • Every thread has a name and priority • Priority range: 1 to 10 Learning multithreading step by step while strengthening Java fundamentals ☕💻 #Java #CoreJava #Multithreading #JavaDeveloper #Concurrency #LearningJourney
To view or add a comment, sign in
-
Day 7 – Queue, Deque & PriorityQueue in Java Collections (Backend Developer Learning Series) Today I revised Queue, Deque, and PriorityQueue from the Java Collection Framework — important data structures used in task scheduling, message queues, and backend processing systems. 📌 What is Queue? Queue is a sub-interface of Collection defined in the java.util package. Queue follows the FIFO principle (First In First Out). ➡ Elements are inserted from the rear (tail) ➡ Elements are removed from the front (head) Example: Insert → 10 20 30 40 Remove → 10 (first inserted element) ⚙ Queue Implementations Some commonly used Queue classes: ✔ LinkedList ✔ PriorityQueue ✔ ArrayDeque 📌 Important Queue Methods 1️⃣ offer() q.offer(40); Adds an element to the rear of the queue. 2️⃣ poll() q.poll(); Removes and returns the head element. 3️⃣ peek() q.peek(); Returns the head element without removing it. 📌 What is Deque? Deque stands for Double Ended Queue. It allows insertion and deletion from both ends. ✔ Insert from front and rear ✔ Remove from front and rear Deque is defined in java.util package. ⚙ Deque Implementations ✔ ArrayDeque ✔ LinkedList 📌 Important Deque Methods Insert Methods offerFirst() offerLast() addFirst() addLast() Remove Methods pollFirst() pollLast() removeFirst() removeLast() Access Methods peekFirst() peekLast() getFirst() getLast() 📌 ArrayDeque ArrayDeque is a class that implements the Deque interface. Key Points ✔ Introduced in JDK 1.6 ✔ Uses resizable array internally ✔ Faster than Stack in many cases ✔ Default capacity = 16 📌 PriorityQueue PriorityQueue is another implementation of the Queue interface. Unlike normal queues, elements are ordered based on priority instead of insertion order. ✔ Default sorting → Natural order (Ascending) ✔ Uses Heap data structure internally ✔ Does NOT allow null values 💻 Example Program – PriorityQueue import java.util.*; public class PriorityQueueExample { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(30); pq.offer(10); pq.offer(50); pq.offer(20); System.out.println(pq); while(!pq.isEmpty()) { System.out.println(pq.poll()); } } } Output 10 20 30 50 Elements are removed in priority order (ascending) PriorityQueue is used in: ✔ Task priority scheduling ✔ Load balancing ✔ Path finding algorithms ✔ CPU scheduling 🧠 Key Learning Queue → FIFO data processing Deque → Flexible queue with operations from both ends PriorityQueue → Processes elements based on priority Understanding these structures helps build efficient backend processing systems. #Java #BackendDeveloper #JavaCollections #Queue #Deque #PriorityQueue #SpringBoot #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
📘 Java Learning – Collections Framework (Part 9: Queue, PriorityQueue, NavigableSet & NavigableMap) 🚦🚀 Continuing my Java Collections series, today I explored collections used for ordering, prioritizing, and navigation of data. 🔰 Queue (I) • Child interface of Collection • Used to hold objects prior to processing • Generally follows FIFO (First In First Out) • From Java 1.5, LinkedList implements Queue • LinkedList-based Queue always follows FIFO 📌 Important Queue Methods • offer() → add element • peek() → returns head (null if empty) • element() → returns head (Exception if empty) • poll() → remove & return head (null if empty) • remove() → remove & return head (Exception if empty) 🧪 Example Queue q = new LinkedList(); q.offer(10); q.offer(20); System.out.println(q.poll()); // 10 🔰 PriorityQueue (C) • Used to process objects based on priority • Priority can be: • Default natural sorting • Custom sorting (Comparator) • Duplicate objects ✅ • Insertion order ❌ • Null insertion ❌ 📌 Sorting Rules • Natural order → objects must be homogeneous & Comparable • Comparator → no such restriction 📌 Constructors PriorityQueue q1 = new PriorityQueue(); PriorityQueue q2 = new PriorityQueue(int capacity); PriorityQueue q3 = new PriorityQueue(int capacity, Comparator c); PriorityQueue q4 = new PriorityQueue(Collection c); PriorityQueue q5 = new PriorityQueue(SortedSet s); 🧪 Example Queue pq = new PriorityQueue(); pq.offer(20); pq.offer(10); pq.offer(30); System.out.println(pq); // Order NOT guaranteed 🔰 NavigableSet (I) • Child interface of SortedSet • Provides navigation support for TreeSet 📌 Important Methods • ceiling(e) → ≥ e • higher(e) → > e • floor(e) → ≤ e • lower(e) → < e • pollFirst(), pollLast() • descendingSet() 🧪 Example NavigableSet ns = new TreeSet(); ns.add(10); ns.add(20); ns.add(30); System.out.println(ns.ceiling(15)); // 20 🔰 NavigableMap (I) • Child interface of SortedMap • Provides navigation methods for TreeMap 📌 Important Methods • ceilingKey() • higherKey() • floorKey() • lowerKey() • pollFirstEntry() • pollLastEntry() • descendingMap() 🧪 Example NavigableMap nm = new TreeMap(); nm.put(1, "Java"); nm.put(3, "Spring"); nm.put(2, "Boot"); System.out.println(nm.floorKey(2)); // 2 ⭐ Key Takeaways • Queue → FIFO processing • PriorityQueue → priority-based processing • NavigableSet → navigation on sorted sets • NavigableMap → navigation on sorted maps Understanding these collections helps in efficient data processing and retrieval 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #Queue #PriorityQueue #NavigableSet #NavigableMap #JavaCollections #LearningJourney
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development