Collectibles
Java collections are reusable data structures that allow devs to store, retreive, and manipulate groups of objects efficiently. (e.g, ArrayList, HashSet, HashMap)
Why use Collectibles?
- They provide a way to store and manage groups of objects.
- They offer built-in methods for common operations like searching, sorting, and filtering.
- They can improve code readability and maintainability.
Types:
- List: An ordered collection that allows duplicates. (e.g., ArrayList, LinkedList)
- Set: An unordered collection that does not allow duplicates. (e.g., HashSet, TreeSet)
- Map: A collection of key-value pairs. (e.g., HashMap, TreeMap)
- Queue: A collection that follows the FIFO (First In First Out) principle. (e.g., LinkedList, PriorityQueue)
- Stack: A collection that follows the LIFO (Last In First Out) principle. (e.g., Stack, ArrayDeque)
- Deque: A double-ended queue that allows insertion and removal from both ends. (e.g., ArrayDeque, LinkedList)
List usage:
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
// Creating a list of strings
List<String> fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Inserting an element at a specific position
fruits.add(1, "Blueberry"); // Inserts "Blueberry" at index 1
// Accessing elements
System.out.println(fruits.get(2)); // Outputs: Banana
// Replacing an element
fruits.set(2, "Blackberry"); // Replaces "Banana" with "Blackberry"
// Removing elements
fruits.remove("Apple"); // Removes "Apple"
fruits.remove(0); // Removes the element at index 0 ("Blueberry")
// Iterating over the list
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
ListExample.main(null);
Banana
Blackberry
Cherry
import java.util.ArrayList;
import java.util.List;
public class ArrayIntegers {
public static void main(String[] args) {
// Create and populate the list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(3);
numbers.add(8);
numbers.add(1);
numbers.add(9);
numbers.add(2);
numbers.add(4);
numbers.add(7);
numbers.add(6);
numbers.add(0);
// Sort the list in numerical order
numbers.sort(null);
// Print the sorted list
System.out.println(numbers);
// remove all odd numbers in for loop
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) % 2 != 0) {
numbers.remove(i);
i--;
}
}
System.out.println(numbers);
}
}
// Call the main method
ArrayIntegers.main(null);
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
Popcorn Hack 2
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
Map<String, String> studentMap = new HashMap<>();
studentMap.put("Torin", "6197565600");
studentMap.put("Jenna", "6197565601");
studentMap.put("Mason", "6197565602");
studentMap.put("Liam", "6197565603");
studentMap.put("Emma", "6197565604");
// Retrieve value by key
System.out.println("Torin's Phone Number: " + studentMap.get("Torin"));
// Iterate using keySet()
System.out.println("Student Roster:");
for (String name : studentMap.keySet()) {
System.out.println(name + ": " + studentMap.get(name));
}
// a search function via scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a student's name to search: ");
System.out.println("");
String searchName = scanner.nextLine();
if (studentMap.containsKey(searchName)) {
System.out.println(searchName + "'s Phone Number: " + studentMap.get(searchName));
} else {
System.out.println("Student not found.");
}
scanner.close();
}
}
HashMapDemo.main(null);
Torin's Phone Number: 6197565600
Student Roster:
Jenna: 6197565601
Mason: 6197565602
Liam: 6197565603
Emma: 6197565604
Torin: 6197565600
Enter a student's name to search:
Torin's Phone Number: 6197565600
Popcorn Hack 3:
import java.util.ArrayDeque;
import java.util.Deque;
public class ArrayDequeFunc {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
// Adding elements
deque.add("First");
deque.add("Second");
deque.add("Third");
// Accessing elements
System.out.println("First element: " + deque.getFirst());
System.out.println("Last element: " + deque.getLast());
// add strings to both ends
deque.addFirst("Zero");
deque.addLast("Fourth");
System.out.println("After adding elements:");
System.out.println("First element: " + deque.getFirst());
System.out.println("Last element: " + deque.getLast());
//remove strings from both ends
deque.removeFirst();
deque.removeLast();
System.out.println("After removing elements:");
System.out.println("First element: " + deque.getFirst());
System.out.println("Last element: " + deque.getLast());
}
}
ArrayDequeFunc.main(null);
First element: First
Last element: Third
After adding elements:
First element: Zero
Last element: Fourth
After removing elements:
First element: First
Last element: Third
Homework Section:
Part 1:
- Create a method named filterEvenNumbers that takes a List
as input and returns a new list containing only the even numbers (in the same order).
Requirements:
- Use ArrayList
. - Use methods: add(), get(), and size().
- Use a traditional loop (do not use streams).
- Intended Output Example:
If the input list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Your program should output:
Input List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Filtered Even Numbers: [2, 4, 6, 8, 10]
public class filterEvenNumbers {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> evenNumbers = new ArrayList<>();
System.out.println("Original list: ");
for (int number : numbers) {
System.out.print(number + " ");
}
System.out.println();
// Filter even numbers
for (int number : numbers) {
if (number % 2 == 0) {
evenNumbers.add(number);
}
}
// utilize size and get
System.out.println("Number of even numbers: " + evenNumbers.size());
System.out.println("First even number: " + evenNumbers.get(0));
System.out.println("Even numbers: " + evenNumbers);
}
}
filterEvenNumbers.main(null);
Original list:
1 2 3 4 5 6 7 8 9 10
Number of even numbers: 5
First even number: 2
Even numbers: [2, 4, 6, 8, 10]
Part 2:
Task:
- Create a method called findIntersection that accepts two Set
objects and returns a new set containing only the common elements (i.e., the intersection).
Requirements:
- Use HashSet
. - Use methods: contains(), add(), and iterate through one of the sets.
- The resulting set should naturally have no duplicates.
- Intended Output Example:
Given:
Set 1: {"apple", "banana", "cherry", "date"}
Set 2: {"banana", "date", "fig", "grape"}
The program should output:
Set1: [apple, banana, cherry, date]
Set2: [banana, date, fig, grape]
Intersection: [banana, date]
public class findIntersection {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
Set<Integer> intersection = new HashSet<>();
// Populate the sets
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
set1.add(5);
set2.add(3);
set2.add(4);
set2.add(5);
set2.add(6);
set2.add(7);
for (Integer num : set1) {
if (set2.contains(num)) {
intersection.add(num);
}
}
System.out.println("Intersection: " + intersection);
}
}
findIntersection.main(null);
Intersection: [3, 4, 5]
Part 3:
Task:
Simulate a line of customers using a Deque
Enqueue: Add 4 customer names to the end of the deque.
- VIP Arrival: A VIP customer arrives—add this customer to the front of the deque.
- Process Line: Remove the customer at the front (simulate serving them).
- Inspect Line: Display the current front and the back of the deque.
- Size Check: Print the size of the deque (the number of customers still in line).
Requirements:
- Use ArrayDeque
. - Utilize these methods: addLast(), addFirst(), removeFirst(), peekFirst(), peekLast(), and size().
- Intended Output Example:
Assume the following names for simulation:
Start with 4 customers added to the end: "Alice", "Bob", "Charlie", "Diana".
Then a VIP customer, "VIP1", is added to the front.
The customer at the front is then removed.
The program should output:
Initial line after adding 4 customers (end): [Alice, Bob, Charlie, Diana]
After VIP arrival (added at front): [VIP1, Alice, Bob, Charlie, Diana]
After serving the customer at the front (removed): [Alice, Bob, Charlie, Diana]
Current front of the line: Alice
Current back of the line: Diana
Total number of customers waiting: 4
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
deque.addLast("Alice");
deque.addLast("Bob");
deque.addLast("Charlie");
deque.addLast("Diana");
System.out.println("Initial line after adding 4 customers (end): " + deque);
deque.addFirst("VIP");
System.out.println("After VIP arrival (added at front): " + deque);
deque.removeFirst();
System.out.println("After serving the customer at the front (removed): " + deque);
System.out.println("Current front of the line: " + deque.peekFirst());
System.out.println("Current back of the line: " + deque.peekLast());
System.out.println("Total number of customers waiting: " + deque.size());
}
}
DequeExample.main(null);
Initial line after adding 4 customers (end): [Alice, Bob, Charlie, Diana]
After VIP arrival (added at front): [VIP, Alice, Bob, Charlie, Diana]
After serving the customer at the front (removed): [Alice, Bob, Charlie, Diana]
Current front of the line: Alice
Current back of the line: Diana
Total number of customers waiting: 4