diff --git a/README.md b/README.md index acd7826..6b3968c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# java-collections + # java-collections # Java Collections Framework Learning Guide This repository is designed to help you learn the **Java Collections Framework step-by-step**. Each section introduces a new concept, provides examples, and gives you practice problems to reinforce what you learned. diff --git a/src/main/java/Collections/Practice/CollectionBasics.java b/src/main/java/Collections/Practice/CollectionBasics.java index e45cb49..cc83a99 100644 --- a/src/main/java/Collections/Practice/CollectionBasics.java +++ b/src/main/java/Collections/Practice/CollectionBasics.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.HashSet; public class CollectionBasics { public static void main(String[] args) { @@ -19,6 +20,8 @@ public static void main(String[] args) { System.out.println("Count of even numbers: " + countEven(numbers)); System.out.println("Largest number: " + findMax(numbers)); System.out.println("Contains duplicates? " + hasDuplicates(numbers)); + System.out.println("Count occurrences of 20 " + countOccurrences(numbers,20)); + System.out.println("Numbers greater than 20: " + filterGreaterThanTwenty(numbers)); } @@ -31,8 +34,9 @@ public static int sum(Collection numbers) { int total = 0; // TODO: - // Loop through the collection - // Add each number to total + for(int num : numbers){ + total+= num; + } return total; } @@ -47,8 +51,11 @@ public static int countEven(Collection numbers) { int count = 0; // TODO: - // Loop through the collection - // If the number is even, increase count + for(int num : numbers){ + if (num % 2 ==0){ + count++; + } + } return count; } @@ -63,8 +70,11 @@ public static int findMax(Collection numbers) { int max = Integer.MIN_VALUE; // TODO: - // Loop through numbers - // Update max if current number is larger + for (int num : numbers){ + if(num > max) { + max = num; + } + } return max; } @@ -78,10 +88,9 @@ public static int findMax(Collection numbers) { public static boolean hasDuplicates(Collection numbers) { // TODO: - // Hint: - // Compare the size of a collection with the size of a Set + HashSet set = new HashSet<>(numbers); - return false; + return set.size() != numbers.size(); } @@ -94,8 +103,12 @@ public static int countOccurrences(Collection numbers, int target) { int count = 0; // TODO: - // Loop through numbers - // If number equals target, increase count + for (int num : numbers){ + + if (num == target ){ + count++; + } + } return count; } @@ -111,8 +124,11 @@ public static Collection filterGreaterThanTwenty(Collection nu Collection result = new ArrayList<>(); // TODO: - // Loop through numbers - // Add numbers greater than 20 to result + for (int num : numbers){ + if (num >20){ + result.add(num); + } + } return result; } diff --git a/src/main/java/Collections/Practice/CommonMethodsDemo.java b/src/main/java/Collections/Practice/CommonMethodsDemo.java index b2dd6f9..fbf9a85 100644 --- a/src/main/java/Collections/Practice/CommonMethodsDemo.java +++ b/src/main/java/Collections/Practice/CommonMethodsDemo.java @@ -125,37 +125,38 @@ public static void main(String[] args) { // TODO Exploration Section // ------------------------------ - /* - TODO 1: - Create a new Collection called numbers - Add the following values: - 10, 20, 30, 40, 50 - */ + //TODO 1: + Collection numbers = new ArrayList<>(); - /* - TODO 2: - Print the size of the numbers collection - */ + numbers.add(10); + numbers.add(20); + numbers.add(30); + numbers.add(40); + numbers.add(50); - /* - TODO 3: - Check if the collection contains 30 - */ + //TODO 2: + System.out.println(numbers.size()); - /* - TODO 4: - Remove the number 20 - */ + //TODO 3: + System.out.println(numbers.contains(30)); - /* - TODO 5: - Loop through the numbers collection - and print each value - */ + + + //TODO 4: + numbers.remove(20); + System.out.println(numbers); + + + + // TODO 5: + + for(int num : numbers){ + System.out.println(num); + } /* diff --git a/src/main/java/Collections/Quiz/KnowledgeCheck.md b/src/main/java/Collections/Quiz/KnowledgeCheck.md index 43ee11f..b68dd1a 100644 --- a/src/main/java/Collections/Quiz/KnowledgeCheck.md +++ b/src/main/java/Collections/Quiz/KnowledgeCheck.md @@ -17,6 +17,8 @@ B. `Collection` extends `List` C. `Collection` is the root interface for most collection types D. `Collection` only stores key-value pairs +AW: C + --- ## Question 2 @@ -37,6 +39,8 @@ B. 1 C. 3 D. 30 +AW: C + --- ## Question 3 @@ -48,6 +52,8 @@ B. `exists()` C. `contains()` D. `check()` +AW:C + --- ## Question 4 @@ -70,6 +76,8 @@ B. `[Jordan]` C. `[Alex]` D. `[]` +AW: B + --- ## Question 5 @@ -81,6 +89,8 @@ B. `addAll()` C. `insertAll()` D. `merge()` +AW:B + --- ## Question 6 @@ -98,6 +108,8 @@ B. `false` C. `0` D. Compilation error +AW:A + --- ## Question 7 @@ -109,6 +121,8 @@ B. `deleteAll()` C. `clear()` D. `reset()` +AW:A + --- ## Question 8 @@ -132,6 +146,8 @@ B. `15 10 5` C. `0 1 2` D. Compilation error +AW:A + --- ## Question 9 @@ -143,6 +159,8 @@ B. Elements can be removed C. Indexed access using `.get(index)` D. Elements can be iterated using a loop +AW:C + --- ## Question 10 @@ -158,5 +176,7 @@ B. It prevents duplicates C. It allows flexibility to change implementations later D. It forces the collection to be synchronized +AW:C + ``` ``` diff --git a/src/main/java/Collections/README.md b/src/main/java/Collections/README.md index a3dfc4f..bd78c82 100644 --- a/src/main/java/Collections/README.md +++ b/src/main/java/Collections/README.md @@ -1,4 +1,4 @@ -```markdown + ```markdown # Collection ## What Is Collection? diff --git a/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java b/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java index 6c2f4e1..9b85024 100644 --- a/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java +++ b/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java @@ -1,16 +1,51 @@ package CollectionsHackerrank; -import java.util.List; -import java.util.Map; -import java.util.Queue; +import java.util.*; public class CollectionsHackerrankProblems { public class CollectionsHackerrankPractice { public static void main(String[] args) { - // You can test your methods here + // Problem 1 + List numbers = Arrays.asList(1,2,2,3,4,4,5); + System.out.println("Remove duplicates: " + removeDuplicates(numbers)); + // Problem 2 + List freqTest = Arrays.asList(1,2,2,3,3,3); + System.out.println("Frequency map: " + countFrequency(freqTest)); + + // Problem 3 + List uniqueTest = Arrays.asList(4,5,1,2,0,4); + System.out.println("First unique: " + firstUnique(uniqueTest)); + + // Problem 4 + List twoSumTest = Arrays.asList(2,7,11,15); + System.out.println("Two Sum = " + twoSum(twoSumTest, 9)); + + // Problem 5 + List words = Arrays.asList("apple","banana","apple","orange"); + System.out.println("Unique words count: " + countUniqueWords(words)); + + // Problem 6 + Queue queue = new LinkedList<>(Arrays.asList(1,2,3,4)); + System.out.println("Reverse queue: " + reverseQueue(queue)); + + // Problem 7 + System.out.println("Balanced parentheses: " + isBalanced("(())")); + System.out.println("Balanced parentheses: " + isBalanced("(()")); + + // Problem 8 + List mostFreq = Arrays.asList(1,3,2,3,4,3); + System.out.println("Most frequent: " + mostFrequent(mostFreq)); + + // Problem 9 + List animals = Arrays.asList("cat","dog","elephant","ant"); + System.out.println("Group by length: " + groupByLength(animals)); + + // Problem 10 + List sliding = Arrays.asList(2,1,5,1,3,2); + System.out.println("Max sliding window sum: " + maxSlidingWindowSum(sliding,3)); } /* @@ -23,9 +58,9 @@ public static void main(String[] args) { */ public static List removeDuplicates(List numbers) { - // TODO: Implement this method + Set unique = new LinkedHashSet<>(numbers); - return null; + return new ArrayList<>(unique); } /* @@ -40,7 +75,42 @@ public static Map countFrequency(List numbers) { // TODO: Implement this method - return null; + //Had chat help me understand some of these and I will try and do some mock problems over the weekend. + + // Create a HashMap to store the results + // Key = the number from the list + // Value = how many times that number appears + Map frequency = new HashMap<>(); + + // Loop through every number inside the list + for (int num : numbers) { + + // Check if the number already exists in the map + // containsKey(num) asks: "Have we seen this number before?" + if (frequency.containsKey(num)) { + + // If the number is already in the map: + // Get its current count and add 1 to it + // Example: + // If map has {2=1} and we see another 2 + // It becomes {2=2} + frequency.put(num, frequency.get(num) + 1); + + } else { + + // If the number is NOT in the map yet + // This means we are seeing it for the first time + // So we add it with a starting count of 1 + // Example: {3=1} + frequency.put(num, 1); + } + + } + + // After the loop finishes, the map contains + // every number and how many times it appeared + // Example: {1=1, 2=2, 3=3} + return frequency; } /* @@ -55,6 +125,30 @@ public static Integer firstUnique(List numbers) { // TODO: Implement this method + // Map to store how many times each number appears + Map frequency = new HashMap<>(); + + // First loop: count each number + for (int num : numbers) { + + if (frequency.containsKey(num)) { + frequency.put(num, frequency.get(num) + 1); + } else { + frequency.put(num, 1); + } + + } + + // Second loop: find the first number that appears only once + for (int num : numbers) { + + if (frequency.get(num) == 1) { + return num; + } + + } + + // If no unique number exists return null; } @@ -69,8 +163,22 @@ public static Integer firstUnique(List numbers) { Output: true */ public static boolean twoSum(List numbers, int target) { + // Store numbers we have already seen + Set seen = new HashSet<>(); - // TODO: Implement this method + for (int num : numbers) { + + // Find the number needed to reach the target + int complement = target - num; + + // If we've already seen the complement + if (seen.contains(complement)) { + return true; + } + + // Otherwise store the current number + seen.add(num); + } return false; } @@ -85,9 +193,9 @@ public static boolean twoSum(List numbers, int target) { */ public static int countUniqueWords(List words) { - // TODO: Implement this method + Set unique = new HashSet<>(words); - return 0; + return unique.size(); } /* @@ -100,11 +208,21 @@ public static int countUniqueWords(List words) { */ public static Queue reverseQueue(Queue queue) { - // TODO: Implement this method - return null; - } + Stack stack = new Stack<>(); + + // Move queue elements to stack + while (!queue.isEmpty()) { + stack.push(queue.poll()); + } + // Move stack elements back to queue + while (!stack.isEmpty()) { + queue.offer(stack.pop()); + } + + return queue; + } /* Problem 7 Determine whether parentheses are balanced. @@ -118,9 +236,25 @@ public static Queue reverseQueue(Queue queue) { */ public static boolean isBalanced(String expression) { - // TODO: Implement this method - return false; + Stack stack = new Stack<>(); + + for (char c : expression.toCharArray()) { + + if (c == '(') { + stack.push(c); + } else if (c == ')') { + + if (stack.isEmpty()) { + return false; + } + + stack.pop(); + } + } + + return stack.isEmpty(); + } } /* @@ -134,8 +268,25 @@ public static boolean isBalanced(String expression) { public static Integer mostFrequent(List numbers) { // TODO: Implement this method + Map frequency = new HashMap<>(); - return null; + for (int num : numbers) { + + frequency.put(num, frequency.getOrDefault(num, 0) + 1); + } + + int maxCount = 0; + Integer result = null; + + for (int num : frequency.keySet()) { + + if (frequency.get(num) > maxCount) { + maxCount = frequency.get(num); + result = num; + } + } + + return result; } /* @@ -154,8 +305,20 @@ public static Integer mostFrequent(List numbers) { public static Map> groupByLength(List words) { // TODO: Implement this method + Map> result = new HashMap<>(); - return null; + for (String word : words) { + + int length = word.length(); + + if (!result.containsKey(length)) { + result.put(length, new ArrayList<>()); + } + + result.get(length).add(word); + } + + return result; } /* @@ -171,8 +334,24 @@ public static Map> groupByLength(List words) { public static int maxSlidingWindowSum(List numbers, int k) { // TODO: Implement this method + int windowSum = 0; - return 0; + for (int i = 0; i < k; i++) { + windowSum += numbers.get(i); + } + + int maxSum = windowSum; + + for (int i = k; i < numbers.size(); i++) { + + windowSum += numbers.get(i); + windowSum -= numbers.get(i - k); + + maxSum = Math.max(maxSum, windowSum); + } + + return maxSum; } } -} + + diff --git a/src/main/java/Hierachy/PRACTICE.md b/src/main/java/Hierachy/PRACTICE.md index 2b885d9..ad77025 100644 --- a/src/main/java/Hierachy/PRACTICE.md +++ b/src/main/java/Hierachy/PRACTICE.md @@ -16,6 +16,8 @@ B. Iterable C. List D. Queue +AW: B + --- ## Question 2 @@ -27,6 +29,8 @@ B. Collection C. Map D. Deque +AW: B + --- ## Question 3 @@ -38,6 +42,8 @@ B. Set C. Queue D. Map +AW: D + --- ## Question 4 @@ -49,6 +55,8 @@ B. List C. Queue D. TreeSet +AW: B + --- ## Question 5 @@ -60,17 +68,19 @@ B. Set C. Queue D. Map +AW: D + --- # True or False Write **True** or **False**. -1. `ArrayList` implements the `List` interface. -2. `Set` allows duplicate elements. -3. `Map` stores elements using keys and values. -4. `Queue` typically follows FIFO behavior. -5. `Iterable` allows collections to be used in enhanced for-loops. +1. `ArrayList` implements the `List` interface. AW: T +2. `Set` allows duplicate elements. AW: F +3. `Map` stores elements using keys and values. AW:T +4. `Queue` typically follows FIFO behavior. AW:T +5. `Iterable` allows collections to be used in enhanced for-loops. AW: T --- @@ -80,6 +90,8 @@ Write **True** or **False**. What is the difference between an **interface** and a **class** in the Java Collections Framework? +AW: Defines behavior + --- ## Question 2 @@ -90,6 +102,9 @@ Example: ```java List list = new ArrayList<>(); + +AW: Because it allows flexibility. + ```` --- @@ -117,9 +132,11 @@ for (String fruit : fruits) { Questions: -1. Which interface type is used for the variable? -2. Which class is used as the implementation? -3. Why can the enhanced for-loop be used here? +1. Which interface type is used for the variable? AW: List +2. Which class is used as the implementation? AW: ArrayList +3. Why can the enhanced for-loop be used here? + +AW: Because List implements Iterable, Iterable allows the collection to be looped through. --- @@ -134,6 +151,40 @@ Create a small program that demonstrates the following: Print the contents of each structure. + // List example + List names = new ArrayList<>(); + names.add("John"); + names.add("Sarah"); + names.add("Mike"); + + System.out.println("List: " + names); + + // Set example + Set numbers = new HashSet<>(); + numbers.add(10); + numbers.add(20); + numbers.add(20); + numbers.add(30); + + System.out.println("Set: " + numbers); + + // Queue example + Queue tasks = new LinkedList<>(); + tasks.offer("Email client"); + tasks.offer("Fix bug"); + tasks.offer("Deploy code"); + + System.out.println("Queue: " + tasks); + + // Map example + Map grades = new HashMap<>(); + grades.put("John", 90); + grades.put("Sarah", 85); + grades.put("Mike", 88); + + System.out.println("Map: " + grades); + + --- # Challenge Exercise diff --git a/src/main/java/Iterable/Examples/ForEachLoopDemo.java b/src/main/java/Iterable/Examples/ForEachLoopDemo.java index a6d2198..258a709 100644 --- a/src/main/java/Iterable/Examples/ForEachLoopDemo.java +++ b/src/main/java/Iterable/Examples/ForEachLoopDemo.java @@ -16,13 +16,17 @@ public static void main(String[] args) { System.out.println("Printing students using a for-each loop:"); // TODO: - // Use a for-each loop to print each student name + for (String student : students) { + System.out.println(student); + } System.out.println("\nPrinting students in uppercase:"); // TODO: - // Use a for-each loop to print each name in uppercase + for (String student : students) { + System.out.println(student.toUpperCase()); + } System.out.println("\nCount the number of students:"); @@ -30,7 +34,9 @@ public static void main(String[] args) { int count = 0; // TODO: - // Use a for-each loop to count how many students are in the list + for (String student : students) { + count++; + } System.out.println("Total students: " + count); } diff --git a/src/main/java/Iterable/Examples/IteratorDemo.java b/src/main/java/Iterable/Examples/IteratorDemo.java index b09fca7..9a9a683 100644 --- a/src/main/java/Iterable/Examples/IteratorDemo.java +++ b/src/main/java/Iterable/Examples/IteratorDemo.java @@ -24,17 +24,23 @@ public static void main(String[] args) { System.out.println("\nIterating using Iterator:"); // TODO: - // Use iterator.hasNext() and iterator.next() - // Print each number + while(iterator.hasNext()){ + Integer num = iterator.next(); + System.out.println(num); + } System.out.println("\nRemoving odd numbers using Iterator"); iterator = numbers.iterator(); - // TODO: - // Use iterator to remove odd numbers - // Remember: use iterator.remove() + while (iterator.hasNext()) { + Integer num = iterator.next(); + + if (num % 2 != 0) { + iterator.remove(); + } + } System.out.println("\nUpdated list:"); diff --git a/src/main/java/Iterable/Practice/IterableWarmups.java b/src/main/java/Iterable/Practice/IterableWarmups.java index 9e9de94..cf778ab 100644 --- a/src/main/java/Iterable/Practice/IterableWarmups.java +++ b/src/main/java/Iterable/Practice/IterableWarmups.java @@ -28,9 +28,9 @@ public static int sum(Iterable numbers) { int total = 0; - // TODO: - // Use a for-each loop to calculate the sum - + for (int num : numbers) { + total += num; + } return total; } @@ -43,9 +43,11 @@ public static int countEven(Iterable numbers) { int count = 0; - // TODO: - // Loop through numbers - // Increment count if number is even + for (int num : numbers) { + if (num % 2 == 0) { + count++; + } + } return count; } @@ -59,9 +61,11 @@ public static int findMax(Iterable numbers) { int max = Integer.MIN_VALUE; - // TODO: - // Loop through numbers - // Update max if current number is larger + for (int num : numbers) { + if (num > max) { + max = num; + } + } return max; } @@ -73,11 +77,19 @@ public static int findMax(Iterable numbers) { */ public static int countMatches(Iterable words, String target) { + // == not for strings. + //start counter + //loop through words + //if word equals target + //increase counter + int count = 0; - // TODO: - // Loop through words - // Compare each word to target + for (String word : words) { + if (word.equals(target)) { + count++; + } + } return count; } diff --git a/src/main/java/Lists/ArrayLists/ArrayListProblems.java b/src/main/java/Lists/ArrayLists/ArrayListProblems.java index baf4dfa..d389a97 100644 --- a/src/main/java/Lists/ArrayLists/ArrayListProblems.java +++ b/src/main/java/Lists/ArrayLists/ArrayListProblems.java @@ -2,7 +2,9 @@ import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; public class ArrayListProblems { public static void main(String[] args) { @@ -35,7 +37,17 @@ public static int sum(List nums) { // TODO: Implement this method - return 0; + int total = 0; + + // Loop through every number in the list + for (int num : nums) { + + // Add the current number to the running total + total += num; + } + + // Return the final sum + return total; } /* @@ -49,8 +61,20 @@ public static int sum(List nums) { public static int countEvens(List nums) { // TODO: Implement this method + int count = 0; + + // Loop through the list + for (int num : nums) { - return 0; + // If the number is even + if (num % 2 == 0) { + + // Increase the counter + count++; + } + } + + return count; } /* @@ -67,6 +91,18 @@ public static int countEvens(List nums) { public static boolean hasDuplicate(List nums) { // TODO: Implement this method + Set seen = new HashSet<>(); + + for (int num : nums) { + + // If we already saw the number + if (seen.contains(num)) { + return true; + } + + // Otherwise add it to the set + seen.add(num); + } return false; } @@ -82,8 +118,18 @@ public static boolean hasDuplicate(List nums) { public static int findMax(List nums) { // TODO: Implement this method + int max = Integer.MIN_VALUE; + + // Loop through numbers + for (int num : nums) { - return 0; + // If current number is bigger than max + if (num > max) { + max = num; + } + } + + return max; } /* @@ -99,7 +145,14 @@ public static int findMax(List nums) { public static List reverse(List nums) { // TODO: Implement this method + List reversed = new ArrayList<>(); + + // Start from the end of the list + for (int i = nums.size() - 1; i >= 0; i--) { + + reversed.add(nums.get(i)); + } - return null; + return reversed; } } diff --git a/src/main/java/Lists/LinkedLists/LinkedListProblems.java b/src/main/java/Lists/LinkedLists/LinkedListProblems.java index 178a2ba..8fc325b 100644 --- a/src/main/java/Lists/LinkedLists/LinkedListProblems.java +++ b/src/main/java/Lists/LinkedLists/LinkedListProblems.java @@ -38,7 +38,8 @@ public static void main(String[] args) { public static void addToFront(LinkedList list, int value) { // TODO: Implement this method - + // Adds value at the beginning of the list + list.addFirst(value); } /* @@ -52,7 +53,8 @@ public static void addToFront(LinkedList list, int value) { public static void addToEnd(LinkedList list, int value) { // TODO: Implement this method - + // Adds value to the end of the list + list.addLast(value); } /* @@ -66,7 +68,8 @@ public static void addToEnd(LinkedList list, int value) { public static void removeFirstElement(LinkedList list) { // TODO: Implement this method - + // Removes the first element + list.removeFirst(); } /* @@ -80,7 +83,8 @@ public static void removeFirstElement(LinkedList list) { public static void removeLastElement(LinkedList list) { // TODO: Implement this method - + // Removes the last element + list.removeLast(); } /* @@ -95,7 +99,8 @@ public static int getFirstElement(LinkedList list) { // TODO: Implement this method - return 0; + // Returns the first element without removing it + return list.getFirst(); } /* @@ -109,7 +114,7 @@ public static int getFirstElement(LinkedList list) { public static int getLastElement(LinkedList list) { // TODO: Implement this method - - return 0; + // Returns the last element without removing it + return list.getLast(); } } diff --git a/src/main/java/Maps/HashMap/HashMapProblems.java b/src/main/java/Maps/HashMap/HashMapProblems.java index 04b5567..9af4cb8 100644 --- a/src/main/java/Maps/HashMap/HashMapProblems.java +++ b/src/main/java/Maps/HashMap/HashMapProblems.java @@ -35,7 +35,8 @@ public static void main(String[] args) { public static void addItem(Map map, String item, int quantity) { // TODO: Implement this method - + // Add the item as the key and quantity as the value + map.put(item, quantity); } /* @@ -49,8 +50,8 @@ public static void addItem(Map map, String item, int quantity) public static int getQuantity(Map map, String item) { // TODO: Implement this method - - return 0; + // Return the quantity associated with the item + return map.get(item); } /* @@ -65,6 +66,8 @@ public static void updateQuantity(Map map, String item, int new // TODO: Implement this method + // Update the quantity for the item + map.put(item, newQuantity); } /* @@ -79,6 +82,8 @@ public static void removeItem(Map map, String item) { // TODO: Implement this method + // Remove the item from the map + map.remove(item); } /* @@ -92,7 +97,22 @@ public static void removeItem(Map map, String item) { public static Map countFrequency(List numbers) { // TODO: Implement this method + Map frequency = new HashMap<>(); + + for (int num : numbers) { + + if (frequency.containsKey(num)) { + + // Increase the count + frequency.put(num, frequency.get(num) + 1); + + } else { + + // First time seeing this number + frequency.put(num, 1); + } + } - return null; + return frequency; } } diff --git a/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java b/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java index dac03cf..df96ad6 100644 --- a/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java +++ b/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java @@ -31,6 +31,8 @@ public static void main(String[] args) { public static void addToFront(ArrayDeque deque, int value) { // TODO: Implement this method + // Add value to the front of the deque + deque.addFirst(value); } @@ -45,7 +47,8 @@ public static void addToFront(ArrayDeque deque, int value) { public static void addToBack(ArrayDeque deque, int value) { // TODO: Implement this method - + // Add value to the end of the deque + deque.addLast(value); } /* @@ -59,7 +62,8 @@ public static void addToBack(ArrayDeque deque, int value) { public static void removeFront(ArrayDeque deque) { // TODO: Implement this method - + // Remove the first element + deque.removeFirst(); } /* @@ -73,7 +77,8 @@ public static void removeFront(ArrayDeque deque) { public static void removeBack(ArrayDeque deque) { // TODO: Implement this method - + // Remove the last element + deque.removeLast(); } /* @@ -88,7 +93,8 @@ public static Integer peekFront(ArrayDeque deque) { // TODO: Implement this method - return null; + // Return the first element without removing it + return deque.peekFirst(); } /* @@ -103,6 +109,8 @@ public static Integer peekBack(ArrayDeque deque) { // TODO: Implement this method - return null; + // Return the last element without removing it + return deque.peekLast(); + } } diff --git a/src/main/java/Sets/HashSet/HashSetProblems.java b/src/main/java/Sets/HashSet/HashSetProblems.java index a36c570..2268ea0 100644 --- a/src/main/java/Sets/HashSet/HashSetProblems.java +++ b/src/main/java/Sets/HashSet/HashSetProblems.java @@ -1,12 +1,30 @@ package Sets.HashSet; +import java.util.HashSet; import java.util.List; import java.util.Set; public class HashSetProblems { public static void main(String[] args) { - // You can test your methods here + Set fruits = new HashSet<>(); + + addElement(fruits, "apple"); + addElement(fruits, "banana"); + addElement(fruits, "apple"); + + System.out.println("Set: " + fruits); + + System.out.println("Contains banana: " + containsValue(fruits,"banana")); + + removeValue(fruits,"apple"); + System.out.println("After removal: " + fruits); + + System.out.println("Unique count: " + getUniqueCount(fruits)); + + List nums = List.of(1,2,2,3,3,3); + System.out.println("Unique numbers: " + getUniqueValues(nums)); + } @@ -21,7 +39,8 @@ public static void main(String[] args) { public static void addElement(Set set, String value) { // TODO: Implement this method - + // Add the value to the set + set.add(value); } /* @@ -35,8 +54,8 @@ public static void addElement(Set set, String value) { public static boolean containsValue(Set set, String value) { // TODO: Implement this method - - return false; + // Return true if value exists in the set + return set.contains(value); } /* @@ -50,6 +69,8 @@ public static boolean containsValue(Set set, String value) { public static void removeValue(Set set, String value) { // TODO: Implement this method + // Remove the value from the set + set.remove(value); } @@ -64,8 +85,8 @@ public static void removeValue(Set set, String value) { public static int getUniqueCount(Set set) { // TODO: Implement this method - - return 0; + // Return the number of unique elements + return set.size(); } /* @@ -80,6 +101,10 @@ public static Set getUniqueValues(List numbers) { // TODO: Implement this method - return null; + // Convert list to HashSet to remove duplicates + Set unique = new HashSet<>(numbers); + + return unique; + } }