📘 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
Java Map Interface & HashMap 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
-
📘 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
-
📘 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
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 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
-
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
-
🚀 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 129 of My Java Learning Journey 😉 Hello LinkedIn family, Today I practiced a logical program to find all vowels from a list of strings using nested loops in Java 💡 This helped me understand how to work with: List of Strings Converting String to char array Checking characters using indexOf() ------------------------------------------------------------------------------------------- 💻 Code: =======> import java.util.*; public class VowelFind { public static void main(String[] args) { List<String> listOfString = Arrays.asList("aab", "xyz", "iiu"); List<Character> vowels = new ArrayList<>(); for (String str : listOfString) { for (char cha : str.toCharArray()) { if ("aeiou".indexOf(cha) != -1) { vowels.add(cha); } } } System.out.println("vowels :" + vowels); } } ------------------------------------------------------------------------------------------- 🖥 Output: =========> vowels : [a, a, i, i, u] 📖 Output Explanation: Input List: ["aab", "xyz", "iiu"] Step 1️⃣ → Convert each string into characters Step 2️⃣ → Check if character exists in "aeiou" Step 3️⃣ → If yes, add to vowels list From: "aab" → a, a "xyz" → no vowels "iiu" → i, i, u Final list: [a, a, i, i, u] 🔎 Important Concept: ✅ toCharArray() → Converts String into character array ✅ "aeiou".indexOf(cha) → Checks if character exists ✅ != -1 → Means character is found ✅ Nested loops → Loop inside loop 💡 Important Tip: Instead of writing multiple OR conditions like: if(cha=='a' || cha=='e' || cha=='i' ...) Using indexOf() makes code cleaner and more readable. This logic can be used in: ✔ Password validation ✔ Text processing ✔ Data filtering ✔ Interview questions What would you improve in this code? 🤔 Should I convert this into Java 8 Stream version next? 😄 Let’s keep learning 🚀 #Java #JavaLearning #CodingJourney #JavaDeveloper #BackendDeveloper #Streams #ProblemSolving #DevOps #Day129 #codewithyuvi #logicalworld
To view or add a comment, sign in
-
-
🚀 Day 127 of My Java Learning Journey 🤩 Hi Friends, Today I learned how to join two lists using Stream API in Java in a clean and modern way. Instead of using loops, we can use Stream.concat() to combine two lists easily. ------------------------------------------------------------------------------------------- 💻 Code ------------> import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class JoinTwoList { public static void main(String[] args) { List<Integer> list1 = List.of(1, 2, 3); List<Integer> list2 = List.of(4, 5, 6); List<Integer> joinList = Stream .concat(list1.stream(), list2.stream()) .collect(Collectors.toList()); System.out.println("Lists are Joined: " + joinList); } } ------------------------------------------------------------------------------------------- 🖥️ Output Lists are Joined: [1, 2, 3, 4, 5, 6] 🔎 Output Explanation list1.stream() converts first list into stream list2.stream() converts second list into stream Stream.concat() merges both streams Collectors.toList() converts the combined stream back into a list So both lists are joined into a single list. 📌 Important Concept 👉 Stream.concat(Stream s1, Stream s2) It is used to combine two streams into one stream. This method is very useful when working with collections in a functional programming style. 💡 Important Tip List.of() creates an immutable list. You cannot modify it (add/remove elements). If you need a modifiable list, wrap it like this: new ArrayList<>(List.of(1,2,3)); 🤔 Have You Tried This? Do you prefer: Using loops to join lists? Or using Stream API? Let me know your approach in the comments 👇 I am consistently improving my Java skills step by step. If you are also learning Java, let’s grow together 💪 #Java #JavaDeveloper #StreamAPI #Programming #CodingJourney #DevOps #BackendDevelopment #LearningEveryday #day127 #codewithyuvi #Logicalworld
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