![]() |
Intro | Lists | Sets | Queues and Deques | Conclusion |
Collectables Interfaces
Java Collections Framework TeamTeach
Core Collection Interfaces
Introduction- Srini
The Java Collections Framework provides a unified structure for working with groups of objects. At its core is the **Collection
Since **Collection
Key Benefits of Using Collections
- Dynamic sizing (unlike arrays)
- Works with any object type using generics
- Common operations like add, remove, and contains
- Allows flexible, reusable code through interfaces
Core Java Collection Implementations
- ArrayList
- Implements: List (which extends Collection)
- Behavior: Ordered, allows duplicates, fast random access
- Example: ArrayList
- HashSet
- Implements: Set (which extends Collection)
- Behavior: Unordered, no duplicates, fast operations using hashing
- Example: HashSet
- LinkedList
- Implements: List, Deque, Queue (all extend Collection)
- Behavior: Ordered, allows duplicates, efficient insert/remove
- Example: LinkedList
- HashMap
- Implements: Map (not part of Collection)
- Behavior: Stores key-value pairs, no duplicate keys, fast lookup via hashing
- Example: HashMap
1. Lists-Srini
What is a List?
- Ordered Collection: Elements are stored in a specific sequence.
- Indexed Access: Elements can be accessed via their index.
- Duplicates Allowed: Lists can contain multiple instances of the same element.
- Insertion Order Preserved: The order of insertion is maintained.
Common Operations
- add(E e): Adds the element to the end of the list.
- add(int index, E element): Inserts the element at the specified index.
- get(int index): Retrieves the element at the specified index.
- set(int index, E element): Replaces the element at the specified index.
- remove(int index): Removes the element at the specified index.
- indexOf(Object o): Finds the first occurrence of the specified element.
- lastIndexOf(Object o): Finds the last occurrence of the specified element.
- subList(int fromIndex, int toIndex): Returns a sublist from the specified range of indices.
Example: Basic List Operations
import java.util.ArrayList;
import java.util.List;
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
System.out.println("Fruits List: " + fruits);
String firstFruit = fruits.get(0);
System.out.println("First Fruit: " + firstFruit);
fruits.set(1, "Blueberry");
System.out.println("Updated List: " + fruits);
fruits.remove(2);
System.out.println("List After Removal: " + fruits);
int index = fruits.indexOf("Mango");
System.out.println("Index of Mango: " + index);
int size = fruits.size();
System.out.println("Size of List: " + size);
boolean hasApple = fruits.contains("Apple");
System.out.println("List contains Apple: " + hasApple);
List<String> sublist = fruits.subList(0, 2);
System.out.println("Sublist: " + sublist);
Fruits List: [Apple, Banana, Orange, Mango]
First Fruit: Apple
Updated List: [Apple, Blueberry, Orange, Mango]
List After Removal: [Apple, Blueberry, Mango]
Index of Mango: 2
Size of List: 3
List contains Apple: true
Sublist: [Apple, Blueberry]
Example: List Iteration
import java.util.ArrayList;
import java.util.List;
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
System.out.println("Using for-each loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
System.out.println("\nUsing regular for loop:");
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
System.out.println("\nUsing Java 8 forEach with Lambda:");
fruits.forEach(fruit -> System.out.println(fruit));
Using for-each loop:
Apple
Banana
Orange
Mango
Using regular for loop:
Apple
Banana
Orange
Mango
Using Java 8 forEach with Lambda:
Apple
Banana
Orange
Mango
How Extending Iterable Ties into Collection
- The Collection interface extends Iterable, meaning all collections (like List, Set, etc.) can be iterated over.
- By implementing the Iterable interface, collections provide the iterator() method, which is used in the enhanced for-loop (for-each loop).
- This allows collections to be traversed without needing to manually manage the index, simplifying iteration.
- The forEach method, introduced in Java 8, also leverages Iterable to iterate over elements using lambda expressions.
2. Sets- Nitin
What is a Set?
- Collection that cannot contain duplicate elements
- Models the mathematical set abstraction
- No guarantees concerning the order of elements
Key Operations
- add(E e): Adds element to the set if not already present
- remove(Object o): Removes specified element if present
- contains(Object o): Returns true if set contains the specified element
- isEmpty(): Returns true if set contains no elements
- size(): Returns the number of elements in the set
- clear(): Removes all elements from the set
Key takeaways
- NO DUPLICATES
- No ORDER
- Operations generally in O(1) for many set implementations
Example: Basic Set Operations
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Duplicate, won't be added!!!
System.out.println("Set after adding elements: " + fruits);
fruits.remove("Banana");
System.out.println("Set after removing 'Banana': " + fruits);
boolean containsOrange = fruits.contains("Orange");
System.out.println("Set contains 'Orange': " + containsOrange);
System.out.println("Size of Set: " + fruits.size());
System.out.println("Is Set empty: " + fruits.isEmpty());
fruits.clear();
System.out.println("Set after clearing: " + fruits);
System.out.println("Is Set empty after clear: " + fruits.isEmpty());
Set after adding elements: [Apple, Orange, Banana]
Set after removing 'Banana': [Apple, Orange]
Set contains 'Orange': true
Size of Set: 2
Is Set empty: false
Set after clearing: []
Is Set empty after clear: true
3. Queues- Tarun
What is a Queue?
- A collection designed for holding elements prior to processing.
- Follows the First-In-First-Out (FIFO) principle: the first element added is the first one to be removed.
- Useful in scenarios like scheduling( QUEUE SYSTEM IN TOOLKIT FOR EXAMPLE ), task processing, or handling events.
Key Operations
- add(E e): Adds an element to the queue. If the queue is full, it throws an exception.
- remove(): Removes and returns the head (first element) of the queue. Throws an exception if the queue is empty.
- peek(): Returns the head of the queue without removing it. Returns null if the queue is empty.
- isEmpty(): Returns true if the queue contains no elements.
- size(): Returns the number of elements in the queue.
- clear(): Removes all elements from the queue.
Example: Basic Queue Operations
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");
System.out.println("Queue after adding elements: " + queue);
String removedElement = queue.remove();
System.out.println("Removed element: " + removedElement);
System.out.println("Queue after removing an element: " + queue);
String firstElement = queue.peek();
System.out.println("First element (peek): " + firstElement);
System.out.println("Size of Queue: " + queue.size());
System.out.println("Is Queue empty: " + queue.isEmpty());
queue.clear();
System.out.println("Queue after clearing: " + queue);
System.out.println("Is Queue empty after clear: " + queue.isEmpty());
Queue after adding elements: [Apple, Banana, Orange]
Removed element: Apple
Queue after removing an element: [Banana, Orange]
First element (peek): Banana
Size of Queue: 2
Is Queue empty: false
Queue after clearing: []
Is Queue empty after clear: true
4. Deques- Tarun
What is a Deque?
- A double-ended queue that allows insertion and removal of elements from both ends
- Supports both FIFO (queue) and LIFO (stack) operations
- More flexible than a standard queue
- Common in sliding window problems, undo features, and scheduling tasks
Key Operations
- addFirst(E e): Inserts element at the front
- addLast(E e): Inserts element at the back
- removeFirst(): Removes and returns the front element
- removeLast(): Removes and returns the back element
- peekFirst(): Returns (but does not remove) the front element
- peekLast(): Returns (but does not remove) the back element
- isEmpty(): Returns true if the deque is empty
- size(): Returns the number of elements
- clear(): Removes all elements from the deque
Key Takeaways
- Two-End Access: Add or remove from both front and back
- Stack + Queue Behavior: Use it like either a stack or a queue
- Flexible & Efficient: Ideal for a variety of algorithmic patterns
- Common Implementations: ArrayDeque, LinkedList
- O(1) Operations: Most operations are constant time with ArrayDeque
Example: Basic Deque Operations
import java.util.Deque;
import java.util.ArrayDeque;
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("B");
deque.addLast("C");
deque.addFirst("A");
deque.addLast("D");
System.out.println(deque);
System.out.println(deque.removeFirst());
System.out.println(deque.removeLast());
System.out.println(deque.peekFirst());
System.out.println(deque.peekLast());
System.out.println(deque.isEmpty());
System.out.println(deque.size());
deque.clear();
System.out.println(deque.isEmpty());
[A, B, C, D]
A
D
B
C
false
2
true
Summary Diagram
Java Collections Homework (due the Wednesday After Spring break)
Objectives
- Practice using List, Set, and Deque
- Understand when and why to use each
- Apply key methods from each collection type
- Practice iteration and conditional logic with collections
Part 1: Working with Lists
Task:
Create a method that takes a List
Requirements:
- Use ArrayList
- Use add, get, and size
- Use a loop (not streams)
Part 2: Working with Sets
Task:
Create a method that takes two Set
Requirements:
- Use HashSet
- Use contains, add, and iteration
- Final result should have no duplicates
Part 3: Working with Deques
Task:
Simulate a line of customers using a Deque
- Add 3 customers to the end
- Add 1 customer to the front (VIP)
- Remove the customer at the front
- Show the current front and back of the line
- Print the size of the line
Requirements:
- Use ArrayDeque
- Use addFirst, addLast, removeFirst, peekFirst, peekLast, and size
Challenge Question (Bonus +0.01)
Question:
You need to store a collection of student IDs where:
- Order doesn’t matter
- You must prevent duplicates
- You often need to check if an ID exists
Which collection type would be most efficient to use and why?