diff --git a/src/main/java/Collections/Practice/CollectionBasics.java b/src/main/java/Collections/Practice/CollectionBasics.java new file mode 100644 index 0000000..e45cb49 --- /dev/null +++ b/src/main/java/Collections/Practice/CollectionBasics.java @@ -0,0 +1,119 @@ +package Collections.Practice; + +import java.util.ArrayList; +import java.util.Collection; + +public class CollectionBasics { + public static void main(String[] args) { + + Collection numbers = new ArrayList<>(); + + numbers.add(4); + numbers.add(8); + numbers.add(15); + numbers.add(16); + numbers.add(23); + numbers.add(42); + + System.out.println("Sum of numbers: " + sum(numbers)); + System.out.println("Count of even numbers: " + countEven(numbers)); + System.out.println("Largest number: " + findMax(numbers)); + System.out.println("Contains duplicates? " + hasDuplicates(numbers)); + } + + + /* + PROBLEM 1 + Return the sum of all numbers in the collection + */ + public static int sum(Collection numbers) { + + int total = 0; + + // TODO: + // Loop through the collection + // Add each number to total + + return total; + } + + + /* + PROBLEM 2 + Count how many numbers are even + */ + public static int countEven(Collection numbers) { + + int count = 0; + + // TODO: + // Loop through the collection + // If the number is even, increase count + + return count; + } + + + /* + PROBLEM 3 + Find the largest number in the collection + */ + public static int findMax(Collection numbers) { + + int max = Integer.MIN_VALUE; + + // TODO: + // Loop through numbers + // Update max if current number is larger + + return max; + } + + + /* + PROBLEM 4 + Return true if the collection contains duplicates + Return false otherwise + */ + public static boolean hasDuplicates(Collection numbers) { + + // TODO: + // Hint: + // Compare the size of a collection with the size of a Set + + return false; + } + + + /* + PROBLEM 5 + Count how many times a target value appears + */ + public static int countOccurrences(Collection numbers, int target) { + + int count = 0; + + // TODO: + // Loop through numbers + // If number equals target, increase count + + return count; + } + + + /* + BONUS PROBLEM + Create and return a new collection + that only contains numbers greater than 20 + */ + public static Collection filterGreaterThanTwenty(Collection numbers) { + + Collection result = new ArrayList<>(); + + // TODO: + // Loop through numbers + // Add numbers greater than 20 to result + + return result; + } +} diff --git a/src/main/java/Collections/Practice/CommonMethodsDemo.java b/src/main/java/Collections/Practice/CommonMethodsDemo.java new file mode 100644 index 0000000..b2dd6f9 --- /dev/null +++ b/src/main/java/Collections/Practice/CommonMethodsDemo.java @@ -0,0 +1,170 @@ +package Collections.Practice; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class CommonMethodsDemo { + public static void main(String[] args) { + + System.out.println("=== COLLECTION COMMON METHODS DEMO ===\n"); + + /* + IMPORTANT CONCEPT: + We are using the Collection interface as the reference type. + The object type is ArrayList. + */ + + Collection fruits = new ArrayList<>(); + + // ------------------------------ + // add() + // ------------------------------ + + System.out.println("Adding elements using add()"); + + fruits.add("Apple"); + fruits.add("Banana"); + fruits.add("Orange"); + fruits.add("Mango"); + + System.out.println("Fruits: " + fruits); + + + // ------------------------------ + // size() + // ------------------------------ + + System.out.println("\nChecking size of collection"); + + int size = fruits.size(); + System.out.println("Size: " + size); + + + // ------------------------------ + // contains() + // ------------------------------ + + System.out.println("\nChecking if collection contains certain items"); + + boolean hasApple = fruits.contains("Apple"); + boolean hasGrape = fruits.contains("Grape"); + + System.out.println("Contains Apple? " + hasApple); + System.out.println("Contains Grape? " + hasGrape); + + + // ------------------------------ + // remove() + // ------------------------------ + + System.out.println("\nRemoving an element"); + + fruits.remove("Banana"); + + System.out.println("After removing Banana:"); + System.out.println(fruits); + + + // ------------------------------ + // addAll() + // ------------------------------ + + System.out.println("\nAdding multiple elements using addAll()"); + + List moreFruits = new ArrayList<>(); + moreFruits.add("Pineapple"); + moreFruits.add("Strawberry"); + moreFruits.add("Peach"); + + fruits.addAll(moreFruits); + + System.out.println("After addAll:"); + System.out.println(fruits); + + + // ------------------------------ + // Iterating through Collection + // ------------------------------ + + System.out.println("\nLooping through collection:"); + + for (String fruit : fruits) { + System.out.println(fruit); + } + + + // ------------------------------ + // isEmpty() + // ------------------------------ + + System.out.println("\nChecking if collection is empty"); + + boolean empty = fruits.isEmpty(); + System.out.println("Is empty? " + empty); + + + // ------------------------------ + // clear() + // ------------------------------ + + System.out.println("\nClearing the collection"); + + fruits.clear(); + + System.out.println("After clear:"); + System.out.println(fruits); + + + System.out.println("\nCheck if empty after clear:"); + + System.out.println("Is empty? " + fruits.isEmpty()); + + + // ------------------------------ + // TODO Exploration Section + // ------------------------------ + + /* + TODO 1: + Create a new Collection called numbers + Add the following values: + 10, 20, 30, 40, 50 + */ + + + /* + TODO 2: + Print the size of the numbers collection + */ + + + /* + TODO 3: + Check if the collection contains 30 + */ + + + /* + TODO 4: + Remove the number 20 + */ + + + /* + TODO 5: + Loop through the numbers collection + and print each value + */ + + + /* + REFLECTION QUESTIONS: + + 1. Why can we use Collection as the reference type? + 2. What methods are available because of the Collection interface? + 3. What methods are NOT available when using Collection instead of List? + */ + } + +} diff --git a/src/main/java/Collections/Quiz/KnowledgeCheck.md b/src/main/java/Collections/Quiz/KnowledgeCheck.md new file mode 100644 index 0000000..43ee11f --- /dev/null +++ b/src/main/java/Collections/Quiz/KnowledgeCheck.md @@ -0,0 +1,162 @@ +````md +# Quiz.md + +# Java Collections Framework Quiz — Collection Interface + +## Instructions +Answer the following **10 questions** about the **Java `Collection` interface** and common collection methods. +Select the **best answer** for each question. + +--- + +## Question 1 +Which of the following is **true** about the `Collection` interface? + +A. `Collection` is a class +B. `Collection` extends `List` +C. `Collection` is the root interface for most collection types +D. `Collection` only stores key-value pairs + +--- + +## Question 2 +What will the following code print? + +```java +Collection numbers = new ArrayList<>(); + +numbers.add(10); +numbers.add(20); +numbers.add(30); + +System.out.println(numbers.size()); +```` + +A. 0 +B. 1 +C. 3 +D. 30 + +--- + +## Question 3 + +Which method is used to **check if an element exists** inside a collection? + +A. `search()` +B. `exists()` +C. `contains()` +D. `check()` + +--- + +## Question 4 + +What will the following code print? + +```java +Collection names = new ArrayList<>(); + +names.add("Alex"); +names.add("Jordan"); + +names.remove("Alex"); + +System.out.println(names); +``` + +A. `[Alex, Jordan]` +B. `[Jordan]` +C. `[Alex]` +D. `[]` + +--- + +## Question 5 + +Which method adds **all elements from another collection** into an existing collection? + +A. `add()` +B. `addAll()` +C. `insertAll()` +D. `merge()` + +--- + +## Question 6 + +What will the following code print? + +```java +Collection numbers = new ArrayList<>(); + +System.out.println(numbers.isEmpty()); +``` + +A. `true` +B. `false` +C. `0` +D. Compilation error + +--- + +## Question 7 + +Which method removes **all elements** from a collection? + +A. `removeAll()` +B. `deleteAll()` +C. `clear()` +D. `reset()` + +--- + +## Question 8 + +What will the following code print? + +```java +Collection nums = new ArrayList<>(); + +nums.add(5); +nums.add(10); +nums.add(15); + +for(Integer n : nums) { + System.out.print(n + " "); +} +``` + +A. `5 10 15` +B. `15 10 5` +C. `0 1 2` +D. Compilation error + +--- + +## Question 9 + +Which of the following **cannot be guaranteed** when using the `Collection` interface? + +A. Elements can be added +B. Elements can be removed +C. Indexed access using `.get(index)` +D. Elements can be iterated using a loop + +--- + +## Question 10 + +What is the **main benefit** of writing code like this? + +```java +Collection fruits = new ArrayList<>(); +``` + +A. It automatically sorts the collection +B. It prevents duplicates +C. It allows flexibility to change implementations later +D. It forces the collection to be synchronized + +``` +``` diff --git a/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java b/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java new file mode 100644 index 0000000..6c2f4e1 --- /dev/null +++ b/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java @@ -0,0 +1,178 @@ +package CollectionsHackerrank; + +import java.util.List; +import java.util.Map; +import java.util.Queue; + +public class CollectionsHackerrankProblems { + public class CollectionsHackerrankPractice { + + public static void main(String[] args) { + + // You can test your methods here + + } + + /* + Problem 1 + Remove duplicates from a list of integers. + + Example + Input: [1,2,2,3,4,4,5] + Output: [1,2,3,4,5] + */ + public static List removeDuplicates(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 2 + Count how many times each number appears. + + Example + Input: [1,2,2,3,3,3] + Output: {1=1, 2=2, 3=3} + */ + public static Map countFrequency(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 3 + Return the first number that appears only once. + + Example + Input: [4,5,1,2,0,4] + Output: 5 + */ + public static Integer firstUnique(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 4 + Return true if any two numbers add up to the target. + + Example + numbers = [2,7,11,15] + target = 9 + + Output: true + */ + public static boolean twoSum(List numbers, int target) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 5 + Count how many unique words exist in a list. + + Example + Input: ["apple","banana","apple","orange"] + Output: 3 + */ + public static int countUniqueWords(List words) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 6 + Reverse a queue. + + Example + Input: [1,2,3,4] + Output: [4,3,2,1] + */ + public static Queue reverseQueue(Queue queue) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 7 + Determine whether parentheses are balanced. + + Example + Input: "(())" + Output: true + + Input: "(()" + Output: false + */ + public static boolean isBalanced(String expression) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 8 + Return the number that appears most frequently in the list. + + Example + Input: [1,3,2,3,4,3] + Output: 3 + */ + public static Integer mostFrequent(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 9 + Group words based on their length. + + Example + Input: ["cat","dog","elephant","ant"] + + Output: + { + 3 = ["cat","dog","ant"], + 8 = ["elephant"] + } + */ + public static Map> groupByLength(List words) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 10 + Return the maximum sum of any window of size k. + + Example + numbers = [2,1,5,1,3,2] + k = 3 + + Output: 9 + */ + public static int maxSlidingWindowSum(List numbers, int k) { + + // TODO: Implement this method + + return 0; + } + } +} diff --git a/src/main/java/Lists/ArrayLists/ArrayListDemo.java b/src/main/java/Lists/ArrayLists/ArrayListDemo.java new file mode 100644 index 0000000..a63259f --- /dev/null +++ b/src/main/java/Lists/ArrayLists/ArrayListDemo.java @@ -0,0 +1,47 @@ +package Lists.ArrayLists; + +import java.util.ArrayList; +import java.util.List; + +public class ArrayListDemo { + public static void main(String[] args) { + + // Creating an ArrayList + List students = new ArrayList<>(); + + // Adding elements + students.add("Jordan"); + students.add("Taylor"); + students.add("Morgan"); + students.add("Alex"); + + System.out.println("Students: " + students); + + // Access element + System.out.println("First student: " + students.get(0)); + + // Update element + students.set(2, "Chris"); + System.out.println("After update: " + students); + + // Remove element + students.remove("Alex"); + System.out.println("After removal: " + students); + + // Size of list + System.out.println("Total students: " + students.size()); + + // Loop through ArrayList + System.out.println("\nLooping through students:"); + + for (String student : students) { + System.out.println(student); + } + + // Check if element exists + if (students.contains("Jordan")) { + System.out.println("\nJordan is in the list."); + } + } + +} diff --git a/src/main/java/Lists/ArrayLists/ArrayListProblems.java b/src/main/java/Lists/ArrayLists/ArrayListProblems.java new file mode 100644 index 0000000..baf4dfa --- /dev/null +++ b/src/main/java/Lists/ArrayLists/ArrayListProblems.java @@ -0,0 +1,105 @@ +package Lists.ArrayLists; + + +import java.util.ArrayList; +import java.util.List; + +public class ArrayListProblems { + public static void main(String[] args) { + + List numbers = new ArrayList<>(); + + numbers.add(4); + numbers.add(7); + numbers.add(2); + numbers.add(7); + numbers.add(9); + numbers.add(4); + + System.out.println("Sum: " + sum(numbers)); + System.out.println("Even Count: " + countEvens(numbers)); + System.out.println("Contains Duplicate: " + hasDuplicate(numbers)); + System.out.println("Max Value: " + findMax(numbers)); + System.out.println("Reversed List: " + reverse(numbers)); + } + + /* + Problem 1 + Return the sum of all numbers in the list. + + Example + Input: [1,2,3] + Output: 6 + */ + public static int sum(List nums) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 2 + Count how many EVEN numbers exist in the list. + + Example + Input: [1,2,4,7] + Output: 2 + */ + public static int countEvens(List nums) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 3 + Determine if the list contains any duplicate values. + + Example + Input: [1,2,3,1] + Output: true + + Input: [1,2,3] + Output: false + */ + public static boolean hasDuplicate(List nums) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 4 + Return the largest number in the list. + + Example + Input: [4,2,7] + Output: 7 + */ + public static int findMax(List nums) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 5 + Return a NEW list that contains the elements of the original list in reverse order. + + Example + Input: [1,2,3] + Output: [3,2,1] + + The original list should remain unchanged. + */ + public static List reverse(List nums) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Lists/LinkedLists/LinkedListDemo.java b/src/main/java/Lists/LinkedLists/LinkedListDemo.java new file mode 100644 index 0000000..f53bda6 --- /dev/null +++ b/src/main/java/Lists/LinkedLists/LinkedListDemo.java @@ -0,0 +1,44 @@ +package Lists.LinkedLists; + +import java.util.LinkedList; + +public class LinkedListDemo { + public static void main(String[] args) { + + LinkedList tasks = new LinkedList<>(); + + // Adding elements + tasks.add("Check emails"); + tasks.add("Review pull requests"); + tasks.add("Write documentation"); + + System.out.println("Tasks: " + tasks); + + // Add to beginning + tasks.addFirst("Morning standup"); + + // Add to end + tasks.addLast("End of day report"); + + System.out.println("Updated Tasks: " + tasks); + + // Access first and last elements + System.out.println("First Task: " + tasks.getFirst()); + System.out.println("Last Task: " + tasks.getLast()); + + // Remove first element + tasks.removeFirst(); + + // Remove last element + tasks.removeLast(); + + System.out.println("After removals: " + tasks); + + // Loop through LinkedList + System.out.println("\nIterating through tasks:"); + + for (String task : tasks) { + System.out.println(task); + } + } +} diff --git a/src/main/java/Lists/LinkedLists/LinkedListProblems.java b/src/main/java/Lists/LinkedLists/LinkedListProblems.java new file mode 100644 index 0000000..178a2ba --- /dev/null +++ b/src/main/java/Lists/LinkedLists/LinkedListProblems.java @@ -0,0 +1,115 @@ +package Lists.LinkedLists; + +import java.util.LinkedList; + +public class LinkedListProblems { + public static void main(String[] args) { + + LinkedList numbers = new LinkedList<>(); + + numbers.add(10); + numbers.add(20); + numbers.add(30); + numbers.add(40); + numbers.add(50); + + addToFront(numbers, 5); + addToEnd(numbers, 60); + + System.out.println("List after additions: " + numbers); + + removeFirstElement(numbers); + removeLastElement(numbers); + + System.out.println("List after removals: " + numbers); + + System.out.println("First Element: " + getFirstElement(numbers)); + System.out.println("Last Element: " + getLastElement(numbers)); + } + + /* + Problem 1 + Add a value to the FRONT of the LinkedList. + + Example + Input: [10,20,30], value=5 + Output: [5,10,20,30] + */ + public static void addToFront(LinkedList list, int value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Add a value to the END of the LinkedList. + + Example + Input: [10,20,30], value=40 + Output: [10,20,30,40] + */ + public static void addToEnd(LinkedList list, int value) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove the FIRST element from the LinkedList. + + Example + Input: [10,20,30] + Output: [20,30] + */ + public static void removeFirstElement(LinkedList list) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Remove the LAST element from the LinkedList. + + Example + Input: [10,20,30] + Output: [10,20] + */ + public static void removeLastElement(LinkedList list) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Return the FIRST element in the LinkedList. + + Example + Input: [10,20,30] + Output: 10 + */ + public static int getFirstElement(LinkedList list) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 6 + Return the LAST element in the LinkedList. + + Example + Input: [10,20,30] + Output: 30 + */ + public static int getLastElement(LinkedList list) { + + // TODO: Implement this method + + return 0; + } +} diff --git a/src/main/java/Maps/HashMap/HashMapDemo.java b/src/main/java/Maps/HashMap/HashMapDemo.java new file mode 100644 index 0000000..53df45b --- /dev/null +++ b/src/main/java/Maps/HashMap/HashMapDemo.java @@ -0,0 +1,53 @@ +package Maps.HashMap; + +import java.util.HashMap; +import java.util.Map; + +public class HashMapDemo { + public static void main(String[] args) { + + Map studentScores = new HashMap<>(); + + // Adding key-value pairs + studentScores.put("Jordan", 92); + studentScores.put("Taylor", 85); + studentScores.put("Morgan", 88); + + System.out.println("Student Scores: " + studentScores); + + // Access value by key + int score = studentScores.get("Jordan"); + System.out.println("Jordan's Score: " + score); + + // Check if key exists + if (studentScores.containsKey("Taylor")) { + System.out.println("Taylor is in the map."); + } + + // Update value + studentScores.put("Morgan", 90); + System.out.println("Updated Scores: " + studentScores); + + // Remove entry + studentScores.remove("Taylor"); + System.out.println("After Removal: " + studentScores); + + // Loop through keys + System.out.println("\nKeys:"); + for (String key : studentScores.keySet()) { + System.out.println(key); + } + + // Loop through values + System.out.println("\nValues:"); + for (Integer value : studentScores.values()) { + System.out.println(value); + } + + // Loop through entries + System.out.println("\nEntries:"); + for (Map.Entry entry : studentScores.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + } +} diff --git a/src/main/java/Maps/HashMap/HashMapProblems.java b/src/main/java/Maps/HashMap/HashMapProblems.java new file mode 100644 index 0000000..04b5567 --- /dev/null +++ b/src/main/java/Maps/HashMap/HashMapProblems.java @@ -0,0 +1,98 @@ +package Maps.HashMap; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HashMapProblems { + public static void main(String[] args) { + + Map inventory = new HashMap<>(); + + addItem(inventory, "Apples", 10); + addItem(inventory, "Bananas", 5); + addItem(inventory, "Oranges", 8); + + System.out.println("Inventory: " + inventory); + + System.out.println("Quantity of Apples: " + getQuantity(inventory, "Apples")); + + updateQuantity(inventory, "Bananas", 12); + System.out.println("Updated Inventory: " + inventory); + + removeItem(inventory, "Oranges"); + System.out.println("After Removal: " + inventory); + } + + /* + Problem 1 + Add an item and its quantity to the map. + + Example + Input: ("Apples", 10) + Output: {"Apples"=10} + */ + public static void addItem(Map map, String item, int quantity) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Return the quantity of a specific item. + + Example + Input: ("Apples") + Output: 10 + */ + public static int getQuantity(Map map, String item) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 3 + Update the quantity of an existing item. + + Example + Input: ("Bananas", 12) + Output: {"Bananas"=12} + */ + public static void updateQuantity(Map map, String item, int newQuantity) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Remove an item from the map. + + Example + Input: ("Oranges") + Output: item removed + */ + public static void removeItem(Map map, String item) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Count how many times each number appears in a list. + + Example + Input: [1,2,2,3,3,3] + Output: {1=1, 2=2, 3=3} + */ + public static Map countFrequency(List numbers) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Maps/LinkedHashMap/LinkedHashMapDemo.java b/src/main/java/Maps/LinkedHashMap/LinkedHashMapDemo.java new file mode 100644 index 0000000..dead1c0 --- /dev/null +++ b/src/main/java/Maps/LinkedHashMap/LinkedHashMapDemo.java @@ -0,0 +1,37 @@ +package Maps.LinkedHashMap; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class LinkedHashMapDemo { + public static void main(String[] args) { + + Map scores = new LinkedHashMap<>(); + + // Adding key-value pairs + scores.put("Jordan", 95); + scores.put("Taylor", 87); + scores.put("Morgan", 90); + scores.put("Alex", 82); + + System.out.println("Scores: " + scores); + + // Notice the insertion order is preserved + System.out.println("\nIterating through entries:"); + + for (Map.Entry entry : scores.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + + // Updating a value + scores.put("Taylor", 91); + System.out.println("\nAfter updating Taylor: " + scores); + + // Removing a key + scores.remove("Alex"); + System.out.println("\nAfter removing Alex: " + scores); + + // Accessing values + System.out.println("\nJordan's Score: " + scores.get("Jordan")); + } +} diff --git a/src/main/java/Maps/LinkedHashMap/LinkedHashMapProblems.java b/src/main/java/Maps/LinkedHashMap/LinkedHashMapProblems.java new file mode 100644 index 0000000..e8bbdc2 --- /dev/null +++ b/src/main/java/Maps/LinkedHashMap/LinkedHashMapProblems.java @@ -0,0 +1,97 @@ +package Maps.LinkedHashMap; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class LinkedHashMapProblems { + public static void main(String[] args) { + + Map studentGrades = new LinkedHashMap<>(); + + addStudent(studentGrades, "Jordan", 90); + addStudent(studentGrades, "Taylor", 85); + addStudent(studentGrades, "Morgan", 88); + + System.out.println("Students: " + studentGrades); + + updateGrade(studentGrades, "Taylor", 92); + System.out.println("Updated Grades: " + studentGrades); + + removeStudent(studentGrades, "Morgan"); + System.out.println("After Removal: " + studentGrades); + } + + /* + Problem 1 + Add a student and their grade to the LinkedHashMap. + + Example + Input: ("Jordan", 90) + Output: {"Jordan"=90} + */ + public static void addStudent(Map map, String name, int grade) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Update the grade of an existing student. + + Example + Input: ("Taylor", 92) + Output: {"Taylor"=92} + */ + public static void updateGrade(Map map, String name, int newGrade) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove a student from the LinkedHashMap. + + Example + Input: ("Morgan") + Output: Student removed from map + */ + public static void removeStudent(Map map, String name) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Return the first student inserted into the LinkedHashMap. + + Example + Input: {"Jordan"=90, "Taylor"=85} + Output: "Jordan" + */ + public static String getFirstInserted(Map map) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 5 + Given a list of words, return a LinkedHashMap that counts + how many times each word appears while preserving insertion order. + + Example + Input: ["apple","banana","apple","orange"] + Output: {apple=2, banana=1, orange=1} + */ + public static Map wordFrequency(List words) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Maps/TreeMap/TreeMapDemo.java b/src/main/java/Maps/TreeMap/TreeMapDemo.java new file mode 100644 index 0000000..0a0fdd5 --- /dev/null +++ b/src/main/java/Maps/TreeMap/TreeMapDemo.java @@ -0,0 +1,37 @@ +package Maps.TreeMap; + +import java.util.Map; +import java.util.TreeMap; + +public class TreeMapDemo { + public static void main(String[] args) { + + Map leaderboard = new TreeMap<>(); + + // Adding elements + leaderboard.put(3, "Jordan"); + leaderboard.put(1, "Taylor"); + leaderboard.put(4, "Morgan"); + leaderboard.put(2, "Alex"); + + System.out.println("Leaderboard (Sorted by Key): " + leaderboard); + + // Access a value + System.out.println("Rank 1: " + leaderboard.get(1)); + + // First and last keys + System.out.println("First Key: " + ((TreeMap) leaderboard).firstKey()); + System.out.println("Last Key: " + ((TreeMap) leaderboard).lastKey()); + + // Iterating through entries + System.out.println("\nLeaderboard Rankings:"); + + for (Map.Entry entry : leaderboard.entrySet()) { + System.out.println("Rank " + entry.getKey() + ": " + entry.getValue()); + } + + // Removing an entry + leaderboard.remove(2); + System.out.println("\nAfter removing rank 2: " + leaderboard); + } +} diff --git a/src/main/java/Maps/TreeMap/TreeMapProblems.java b/src/main/java/Maps/TreeMap/TreeMapProblems.java new file mode 100644 index 0000000..b101d2e --- /dev/null +++ b/src/main/java/Maps/TreeMap/TreeMapProblems.java @@ -0,0 +1,95 @@ +package Maps.TreeMap; + +import java.util.TreeMap; + +public class TreeMapProblems { + public static void main(String[] args) { + + TreeMap rankings = new TreeMap<>(); + + addPlayer(rankings, 3, "Jordan"); + addPlayer(rankings, 1, "Taylor"); + addPlayer(rankings, 2, "Morgan"); + + System.out.println("Rankings: " + rankings); + + System.out.println("Top Player: " + getTopPlayer(rankings)); + System.out.println("Lowest Ranked Player: " + getLowestPlayer(rankings)); + + removePlayer(rankings, 2); + System.out.println("After removal: " + rankings); + } + + /* + Problem 1 + Add a player to the TreeMap with their rank. + + Example + Input: (1, "Jordan") + Output: {1="Jordan"} + */ + public static void addPlayer(TreeMap map, int rank, String name) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Return the player with the highest ranking (smallest key). + + Example + Input: {1="Jordan", 2="Taylor"} + Output: "Jordan" + */ + public static String getTopPlayer(TreeMap map) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 3 + Return the player with the lowest ranking (largest key). + + Example + Input: {1="Jordan", 2="Taylor"} + Output: "Taylor" + */ + public static String getLowestPlayer(TreeMap map) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 4 + Remove a player based on their rank. + + Example + Input: remove rank 2 + Output: player removed + */ + public static void removePlayer(TreeMap map, int rank) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Return the next higher rank after the given rank. + + Example + Input: rank=2, map={1="A",2="B",3="C"} + Output: 3 + */ + public static Integer getNextRank(TreeMap map, int rank) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Queues/ArrayDeque/ArrayDequeDemo.java b/src/main/java/Queues/ArrayDeque/ArrayDequeDemo.java new file mode 100644 index 0000000..f498386 --- /dev/null +++ b/src/main/java/Queues/ArrayDeque/ArrayDequeDemo.java @@ -0,0 +1,44 @@ +package Queues.ArrayDeque; + +import java.util.ArrayDeque; + +public class ArrayDequeDemo { + public static void main(String[] args) { + + ArrayDeque tasks = new ArrayDeque<>(); + + // Using ArrayDeque as a Queue (FIFO) + tasks.add("Task 1"); + tasks.add("Task 2"); + tasks.add("Task 3"); + + System.out.println("Queue Behavior: " + tasks); + + System.out.println("Removing from queue: " + tasks.poll()); + System.out.println("Queue after poll: " + tasks); + + // Using ArrayDeque as a Stack (LIFO) + ArrayDeque stack = new ArrayDeque<>(); + + stack.push(10); + stack.push(20); + stack.push(30); + + System.out.println("\nStack Behavior: " + stack); + + System.out.println("Pop element: " + stack.pop()); + System.out.println("Stack after pop: " + stack); + + // Adding to front and back + ArrayDeque deque = new ArrayDeque<>(); + + deque.addFirst("Start"); + deque.addLast("Middle"); + deque.addLast("End"); + + System.out.println("\nDeque behavior: " + deque); + + System.out.println("First element: " + deque.getFirst()); + System.out.println("Last element: " + deque.getLast()); + } +} diff --git a/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java b/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java new file mode 100644 index 0000000..dac03cf --- /dev/null +++ b/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java @@ -0,0 +1,108 @@ +package Queues.ArrayDeque; + +import java.util.ArrayDeque; + +public class ArrayDequeProblems { + public static void main(String[] args) { + + ArrayDeque numbers = new ArrayDeque<>(); + + addToFront(numbers, 10); + addToFront(numbers, 5); + addToBack(numbers, 20); + + System.out.println("Deque: " + numbers); + + removeFront(numbers); + System.out.println("After removing front: " + numbers); + + removeBack(numbers); + System.out.println("After removing back: " + numbers); + } + + /* + Problem 1 + Add a number to the FRONT of the deque. + + Example + Input: value = 5 + Output: [5] + */ + public static void addToFront(ArrayDeque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Add a number to the BACK of the deque. + + Example + Input: value = 10 + Output: [5,10] + */ + public static void addToBack(ArrayDeque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove the element at the FRONT of the deque. + + Example + Input: [5,10,20] + Output: [10,20] + */ + public static void removeFront(ArrayDeque deque) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Remove the element at the BACK of the deque. + + Example + Input: [5,10,20] + Output: [5,10] + */ + public static void removeBack(ArrayDeque deque) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Return the FIRST element in the deque without removing it. + + Example + Input: [5,10,20] + Output: 5 + */ + public static Integer peekFront(ArrayDeque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 6 + Return the LAST element in the deque without removing it. + + Example + Input: [5,10,20] + Output: 20 + */ + public static Integer peekBack(ArrayDeque deque) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Queues/Deque/DequeDemo.java b/src/main/java/Queues/Deque/DequeDemo.java new file mode 100644 index 0000000..b05ca20 --- /dev/null +++ b/src/main/java/Queues/Deque/DequeDemo.java @@ -0,0 +1,39 @@ +package Queues.Deque; + +import java.util.ArrayDeque; +import java.util.Deque; + +public class DequeDemo { + public static void main(String[] args) { + + Deque deque = new ArrayDeque<>(); + + // Add elements to the front + deque.addFirst("B"); + deque.addFirst("A"); + + // Add elements to the back + deque.addLast("C"); + deque.addLast("D"); + + System.out.println("Deque: " + deque); + + // Peek elements + System.out.println("First Element: " + deque.peekFirst()); + System.out.println("Last Element: " + deque.peekLast()); + + // Remove elements + System.out.println("Removed First: " + deque.removeFirst()); + System.out.println("Removed Last: " + deque.removeLast()); + + System.out.println("Deque after removals: " + deque); + + // Iterating through deque + System.out.println("\nIterating through deque:"); + + for (String item : deque) { + System.out.println(item); + } + } +} + diff --git a/src/main/java/Queues/Deque/DequeProblems.java b/src/main/java/Queues/Deque/DequeProblems.java new file mode 100644 index 0000000..7ef0c06 --- /dev/null +++ b/src/main/java/Queues/Deque/DequeProblems.java @@ -0,0 +1,100 @@ +package Queues.Deque; + +import java.util.Deque; + +public class DequeProblems { + public static void main(String[] args) { + + // You can test your methods here + + } + + /* + Problem 1 + Add a value to the FRONT of the deque. + + Example + Input: value = 5 + Output: [5] + */ + public static void addFront(Deque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Add a value to the BACK of the deque. + + Example + Input: value = 10 + Output: [5,10] + */ + public static void addBack(Deque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove and return the FRONT element of the deque. + + Example + Input: [5,10,15] + Output: 5 + */ + public static Integer removeFront(Deque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 4 + Remove and return the BACK element of the deque. + + Example + Input: [5,10,15] + Output: 15 + */ + public static Integer removeBack(Deque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 5 + Return the FRONT element without removing it. + + Example + Input: [5,10,15] + Output: 5 + */ + public static Integer peekFront(Deque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 6 + Return the BACK element without removing it. + + Example + Input: [5,10,15] + Output: 15 + */ + public static Integer peekBack(Deque deque) { + + // TODO: Implement this method + + return null; + } + +} diff --git a/src/main/java/Sets/HashSet/HashSetDemo.java b/src/main/java/Sets/HashSet/HashSetDemo.java new file mode 100644 index 0000000..034d7bf --- /dev/null +++ b/src/main/java/Sets/HashSet/HashSetDemo.java @@ -0,0 +1,39 @@ +package Sets.HashSet; + +import java.util.HashSet; +import java.util.Set; + +public class HashSetDemo { + public static void main(String[] args) { + + Set fruits = new HashSet<>(); + + // Adding elements + fruits.add("Apple"); + fruits.add("Banana"); + fruits.add("Orange"); + fruits.add("Apple"); // duplicate + + System.out.println("Fruits: " + fruits); + + // Checking if element exists + if (fruits.contains("Banana")) { + System.out.println("Banana exists in the set."); + } + + // Removing an element + fruits.remove("Orange"); + + System.out.println("After removal: " + fruits); + + // Size of the set + System.out.println("Total unique fruits: " + fruits.size()); + + // Iterating through the set + System.out.println("\nIterating through set:"); + + for (String fruit : fruits) { + System.out.println(fruit); + } + } +} diff --git a/src/main/java/Sets/HashSet/HashSetProblems.java b/src/main/java/Sets/HashSet/HashSetProblems.java new file mode 100644 index 0000000..a36c570 --- /dev/null +++ b/src/main/java/Sets/HashSet/HashSetProblems.java @@ -0,0 +1,85 @@ +package Sets.HashSet; + +import java.util.List; +import java.util.Set; + +public class HashSetProblems { + public static void main(String[] args) { + + // You can test your methods here + + } + + /* + Problem 1 + Add an element to the set. + + Example + Input: "apple" + Output: {"apple"} + */ + public static void addElement(Set set, String value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Check if the set contains a value. + + Example + Input: "banana" + Output: true or false + */ + public static boolean containsValue(Set set, String value) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 3 + Remove a value from the set. + + Example + Input: "apple" + Output: value removed + */ + public static void removeValue(Set set, String value) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Return the number of unique elements in the set. + + Example + Input: {"apple","banana","apple"} + Output: 2 + */ + public static int getUniqueCount(Set set) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 5 + Given a list of integers, return a HashSet containing only the unique values. + + Example + Input: [1,2,2,3,3,3] + Output: {1,2,3} + */ + public static Set getUniqueValues(List numbers) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Sets/HashSet/README.md b/src/main/java/Sets/HashSet/README.md new file mode 100644 index 0000000..e2e1df7 --- /dev/null +++ b/src/main/java/Sets/HashSet/README.md @@ -0,0 +1,177 @@ +````markdown +# HashSet (Condensed Guide) + +## What Is HashSet? + +`HashSet` is a `Set` implementation that stores **unique elements using hashing**. + +Key characteristics: +- No duplicate elements +- No guaranteed ordering +- Allows **one null element** +- Fast lookup, insertion, and removal + +```java +import java.util.Set; +import java.util.HashSet; + +Set numbers = new HashSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set + ↓ +HashSet +``` + +`HashSet` is one of the most commonly used implementations of the `Set` interface. + +--- + +## How It Works + +`HashSet` uses a **hash table** internally. + +Steps when adding an element: + +1. The element’s `hashCode()` is calculated +2. The hash determines a storage location +3. The element is placed into a bucket + +Because of hashing: + +* Searching is very fast +* Order of elements is **not predictable** + +Example: + +``` +add(10) +add(20) +add(10) +``` + +Result: + +``` +10, 20 +``` + +Duplicate values are ignored. + +--- + +## Time Complexity + +| Operation | Complexity | +| ------------ | ------------ | +| `add()` | O(1) average | +| `remove()` | O(1) average | +| `contains()` | O(1) average | + +Worst case (many collisions) → O(n) + +--- + +## Core Methods + +```java +set.add(10); // add element +set.remove(10); // remove element +set.contains(10); // check element +set.size(); // number of elements +set.isEmpty(); // check if empty +``` + +--- + +## Looping Through a HashSet + +```java +for (Integer num : set) { + System.out.println(num); +} +``` + +Because HashSet does not guarantee ordering, elements may appear in any order. + +--- + +## HashSet vs LinkedHashSet vs TreeSet + +| Feature | HashSet | LinkedHashSet | TreeSet | +| -------- | -------------- | ---------------------- | --------------------- | +| Order | None | Insertion order | Sorted | +| Speed | Fastest | Slightly slower | Slower | +| Use Case | Unique storage | Ordered unique storage | Sorted unique storage | + +--- + +## When To Use HashSet + +Use HashSet when you need: + +* Unique elements +* Fast membership checking +* Removing duplicates + +Examples: + +* Unique usernames +* Removing duplicates from a list +* Tracking visited nodes in algorithms +* Fast lookup tables + +--- + +## Example + +```java +Set fruits = new HashSet<>(); + +fruits.add("Apple"); +fruits.add("Banana"); +fruits.add("Apple"); + +System.out.println(fruits); +``` + +Output: + +``` +[Apple, Banana] +``` + +The duplicate `"Apple"` is not stored. + +--- + +## Practice Ideas + +* Remove duplicates from a list +* Count unique numbers in an array +* Track visited nodes in graph traversal +* Compare HashSet with TreeSet ordering + +--- + +## Summary + +HashSet is a **fast implementation of the Set interface that stores unique elements using hashing**. + +Key characteristics: + +* No duplicates +* No guaranteed ordering +* Very fast lookup and insertion + +``` +``` diff --git a/src/main/java/Sets/LinkedHashSet/README.md b/src/main/java/Sets/LinkedHashSet/README.md new file mode 100644 index 0000000..003f3b9 --- /dev/null +++ b/src/main/java/Sets/LinkedHashSet/README.md @@ -0,0 +1,172 @@ +````markdown +# LinkedHashSet (Condensed Guide) + +## What Is LinkedHashSet? + +`LinkedHashSet` is a `Set` implementation that **stores unique elements while maintaining insertion order**. + +Key characteristics: +- No duplicate elements +- Maintains **insertion order** +- Slightly slower than `HashSet` +- Allows **one null element** + +```java +import java.util.Set; +import java.util.LinkedHashSet; + +Set names = new LinkedHashSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set + ↓ +HashSet + ↓ +LinkedHashSet +``` + +`LinkedHashSet` extends `HashSet` but adds **ordering behavior**. + +--- + +## How It Works + +`LinkedHashSet` uses: + +* A **hash table** (like `HashSet`) for fast lookups +* A **doubly linked list** to maintain insertion order + +This allows: + +* Fast operations +* Predictable iteration order + +Example: + +``` +add("A") +add("B") +add("C") +``` + +Iteration order: + +``` +A, B, C +``` + +--- + +## Time Complexity + +| Operation | Complexity | +| ------------ | ------------ | +| `add()` | O(1) average | +| `remove()` | O(1) average | +| `contains()` | O(1) average | + +Performance is similar to `HashSet`, with a small overhead for maintaining order. + +--- + +## Core Methods + +```java +set.add("Apple"); +set.remove("Apple"); +set.contains("Apple"); +set.size(); +set.isEmpty(); +``` + +--- + +## Looping Through a LinkedHashSet + +```java +for (String name : set) { + System.out.println(name); +} +``` + +Elements will appear **in the order they were inserted**. + +--- + +## HashSet vs LinkedHashSet vs TreeSet + +| Feature | HashSet | LinkedHashSet | TreeSet | +| ----------- | ---------------------- | --------------- | --------------- | +| Ordering | None | Insertion order | Sorted | +| Performance | Fastest | Slightly slower | Slower | +| Use Case | General unique storage | Maintain order | Sorted elements | + +--- + +## When To Use LinkedHashSet + +Use LinkedHashSet when you need: + +* Unique elements +* Predictable insertion order +* Fast lookup operations + +Examples: + +* Removing duplicates while preserving order +* Tracking unique user actions +* Maintaining ordered unique logs + +--- + +## Example + +```java +Set fruits = new LinkedHashSet<>(); + +fruits.add("Apple"); +fruits.add("Banana"); +fruits.add("Apple"); + +System.out.println(fruits); +``` + +Output: + +``` +[Apple, Banana] +``` + +The duplicate `"Apple"` is ignored, and the insertion order is preserved. + +--- + +## Practice Ideas + +* Remove duplicates from a list while preserving order +* Store unique usernames in insertion order +* Track unique visited pages + +--- + +## Summary + +LinkedHashSet is a **Set implementation that preserves insertion order while ensuring uniqueness**. + +Key characteristics: + +* No duplicates +* Maintains insertion order +* Fast lookup using hashing + +``` +``` diff --git a/src/main/java/Sets/README.md b/src/main/java/Sets/README.md index e69de29..cfac719 100644 --- a/src/main/java/Sets/README.md +++ b/src/main/java/Sets/README.md @@ -0,0 +1,157 @@ +````markdown +# Set (Condensed Guide) + +## What Is a Set? + +A `Set` is a collection that **does not allow duplicate elements**. + +Key characteristics: +- Stores **unique elements only** +- Does **not support indexing** +- Ordering depends on the implementation + +Common implementations: +- `HashSet` +- `LinkedHashSet` +- `TreeSet` + +```java +import java.util.Set; +import java.util.HashSet; + +Set numbers = new HashSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set +``` + +Implementations include: + +``` +Set + ↓ +HashSet +LinkedHashSet +TreeSet +``` + +--- + +## How It Works + +A `Set` ensures every element is **unique**. + +If you try to insert a duplicate element, it will **not be added**. + +Example: + +``` +add(10) +add(20) +add(20) +add(30) +``` + +Result: + +``` +10, 20, 30 +``` + +The duplicate `20` is ignored. + +--- + +## Time Complexity (Typical HashSet) + +| Operation | Complexity | +| ------------ | ------------ | +| `add()` | O(1) average | +| `remove()` | O(1) average | +| `contains()` | O(1) average | + +Actual performance depends on the implementation. + +--- + +## Core Methods + +```java +set.add(10); // add element +set.remove(10); // remove element +set.contains(10); // check element +set.size(); // number of elements +set.isEmpty(); // check if empty +``` + +--- + +## Looping Through a Set + +```java +for (Integer num : set) { + System.out.println(num); +} +``` + +Sets do not support `get(index)` because they are not indexed. + +--- + +## Set Implementations + +| Implementation | Behavior | +| --------------- | ---------------------------- | +| `HashSet` | No ordering | +| `LinkedHashSet` | Maintains insertion order | +| `TreeSet` | Automatically sorts elements | + +--- + +## Set vs List + +| Feature | List | Set | +| ------------ | --------------- | ------------------------- | +| Duplicates | Allowed | Not allowed | +| Ordering | Maintains order | Depends on implementation | +| Index access | Yes | No | + +--- + +## When To Use Set + +Use a Set when you need: + +* Unique values +* Fast membership checks +* Removing duplicates from data + +Examples: + +* Unique usernames +* Tracking visited items +* Removing duplicate values from lists + +--- + +## Summary + +Set is a **collection that stores unique elements**. + +Key characteristics: + +* No duplicate elements +* No indexing +* Different implementations provide different ordering behavior + +``` +``` diff --git a/src/main/java/Sets/TreeSet/README.md b/src/main/java/Sets/TreeSet/README.md new file mode 100644 index 0000000..c040dc9 --- /dev/null +++ b/src/main/java/Sets/TreeSet/README.md @@ -0,0 +1,219 @@ +````markdown +# TreeSet (Condensed Guide) + +## What Is TreeSet? + +`TreeSet` is a `Set` implementation that **stores unique elements in sorted order**. + +Key characteristics: +- No duplicate elements +- Elements are automatically **sorted** +- Does **not allow null elements** +- Uses a **balanced tree structure** internally + +```java +import java.util.Set; +import java.util.TreeSet; + +Set numbers = new TreeSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set + ↓ +SortedSet + ↓ +NavigableSet + ↓ +TreeSet +``` + +TreeSet implements both `SortedSet` and `NavigableSet`. + +--- + +## How It Works + +`TreeSet` is implemented using a **Red-Black Tree**, a type of self-balancing binary search tree. + +This ensures: + +* Elements remain **sorted** +* Insertions and removals maintain tree balance +* Efficient searching + +Example: + +``` +add(30) +add(10) +add(20) +``` + +Result: + +``` +10, 20, 30 +``` + +Elements are automatically sorted. + +--- + +## Time Complexity + +| Operation | Complexity | +| ------------ | ---------- | +| `add()` | O(log n) | +| `remove()` | O(log n) | +| `contains()` | O(log n) | + +TreeSet is slower than HashSet because it maintains sorted order. + +--- + +## Core Methods + +```java +set.add(10); +set.add(20); +set.add(30); + +set.remove(20); +set.contains(10); +set.size(); +``` + +--- + +## SortedSet Features + +TreeSet allows operations related to ordering. + +### First and Last Elements + +```java +set.first(); +set.last(); +``` + +--- + +### Subsets + +```java +set.subSet(10, 50); +``` + +Returns elements within the specified range. + +--- + +## NavigableSet Features + +### Find Closest Elements + +```java +set.higher(20); // smallest element greater than 20 +set.lower(20); // largest element less than 20 +``` + +### Ceiling and Floor + +```java +set.ceiling(20); // smallest element ≥ 20 +set.floor(20); // largest element ≤ 20 +``` + +--- + +## Looping Through a TreeSet + +```java +for (Integer num : set) { + System.out.println(num); +} +``` + +Elements will always appear **in sorted order**. + +--- + +## TreeSet vs HashSet vs LinkedHashSet + +| Feature | HashSet | LinkedHashSet | TreeSet | +| --------- | ---------- | ----------------- | ------------- | +| Order | None | Insertion order | Sorted | +| Speed | Fastest | Slightly slower | Slower | +| Structure | Hash table | Hash table + list | Balanced tree | + +--- + +## When To Use TreeSet + +Use TreeSet when you need: + +* Automatically **sorted unique elements** +* **Range queries** +* **Closest value searches** + +Examples: + +* Leaderboards +* Sorted indexes +* Range filtering + +--- + +## Example + +```java +Set numbers = new TreeSet<>(); + +numbers.add(50); +numbers.add(10); +numbers.add(30); + +System.out.println(numbers); +``` + +Output: + +``` +[10, 30, 50] +``` + +The elements are stored in sorted order. + +--- + +## Practice Ideas + +* Store numbers and automatically sort them +* Find the smallest and largest elements +* Retrieve values within a range +* Track unique sorted scores + +--- + +## Summary + +TreeSet is a **sorted Set implementation backed by a balanced tree**. + +Key characteristics: + +* Unique elements only +* Automatically sorted +* O(log n) operations +* Supports range and navigation operations + +``` +```