CUCS1004_Module3_Java_Collections_Framework
CUCS1004_Module3_Java_Collections_Framework
• Provides interoperability between unrelated APIs // All collections store objects (wrapper classes for
primitives)
• Fosters software reuse with standard interfaces List<Integer> numbers = new ArrayList<>();
Note: Collections can only store objects, not primitives (use wrapper classes)
Collections Framework Hierarchy
Iterable (interface)
| +-- ArrayList
| +-- LinkedList
| +-- Vector
| +-- HashSet
| +-- LinkedHashSet
| +-- TreeSet
|
Collection vs Collections
Collection (Interface) Collections (Utility Class)
▸ Root interface of collection hierarchy ▸ Utility class with static methods
▸ Defines common methods: add(), remove(), size(), ▸ Provides algorithms for collections
contains()
▸ sort(), binarySearch(), reverse(), shuffle()
▸ Extended by List, Set, Queue interfaces
▸ max(), min(), fill(), copy(), swap()
▸ Cannot be instantiated directly
▸ synchronizedCollection(), unmodifiableCollection()
▸ Represents a group of objects
▸ [Link]
▸ [Link]
02
List Interface
Duration: 3 Hours
List Interface: Ordered Collection
Java Code
Note: List preserves insertion order and allows random access by index
ArrayList: Dynamic Array Implementation
Java Code
// Updating
[Link](2, "JavaScript");
// Removing
[Link]("C++"); // by object
[Link](0); // by index
// Iterating
for (String s : list) {
[Link](s);
}
// Iterating
Iterator<String> it = [Link]();
Note: LinkedList implements List, Deque, and Queue interfaces
while ([Link]()) {
[Link]([Link]());
}
ArrayList vs LinkedList Comparison
Operation ArrayList LinkedList
Thread-safe No No
03
Set Interface
Duration: 2 Hours
Set Interface: Unique Elements Collection
Java Code
// Size
int size = [Link](); // 1
// Union
[Link](set2);
// Intersection
[Link](set2);
// Difference
Note: HashSet is fastest when order doesn't matter and no duplicates needed
[Link](set2);
// Check subset
boolean isSubset = [Link](set2);
TreeSet: Sorted Set Implementation
Java Code
Note: TreeSet is ideal when you need sorted unique elements with range queries
// Subset views
Set<Integer> subset = [Link](20, 50); // [20, 30,
40]
HashSet vs TreeSet vs LinkedHashSet
Feature HashSet TreeSet LinkedHashSet
Use case Fast unique set Sorted unique set Ordered unique set
04
Map Interface
Duration: 3 Hours
Map Interface: Key-Value Pairs
Java Code
// Removing
[Link]("Charlie");
// Size
int size = [Link](); // 2
// Put if absent
[Link]("India", "Mumbai"); // won't
overwrite
// Replace
[Link]("UK", "London", "Manchester");
// Submap views
Map<String, Integer> sub = [Link]("Alice",
"Charlie");
// {Alice=92, Bob=78}
Note: TreeMap is ideal for range queries and sorted key access
// Reverse order TreeMap
TreeMap<String, Integer> reverse = new
TreeMap<>([Link]());
[Link](grades);
HashMap vs TreeMap vs LinkedHashMap
Feature HashMap TreeMap LinkedHashMap
// OR simply:
// return [Link]([Link], [Link]);
}
}
// Usage
List<Student> students = new ArrayList<>();
[Link](new Student(1, "Alice", 85));
[Link](new Student(2, "Bob", 92));
Note: Comparable is in [Link] package (no import needed)
[Link](new Student(3, "Charlie", 78));
// Chaining comparators
Comparator<Student> byMarksThenName = Comparator
.comparingDouble((Student s) -> [Link]).reversed()
.thenComparing(s -> [Link]);
// Usage
[Link](students, byName);
Note: Comparator is more flexible than Comparable; use when multiple sort orders needed
[Link](byId);
[Link](byMarksThenName);
Collections Class: Algorithms & Utilities
Java Code
// Unmodifiable list
07
Generics with Collections
Duration: 1 Hour
Generics: Type-Safe Collections
Java Code
// Generic method
public <T> void printList(List<T> list) {
for (T item : list) {
Note: Always use generics; raw types are for backward compatibility only
[Link](item);
}
}
Wildcards: Flexible Generic Types
Java Code
Note: Each experiment: Problem statement, expected output, code, and conclusion
Experiment 3.1: ArrayList - Student Management
Java Code
// Search by name
for (Student s : students) {
if ([Link]("Alice")) {
[Link]("Found: " + [Link]);
}
}
// Sort by marks
[Link](students);
// Top performer
Student top = [Link](0);
Note: Demonstrate all ArrayList operations: add, remove, get, set, size, contains, indexOf
// Average
double avg = [Link]()
.mapToDouble(s -> [Link])
.average().orElse(0);
Experiment 3.5: HashMap - Word Frequency Counter
Java Code
• Use HashMap<String, Integer> to store word-count pairs HashMap<String, Integer> frequency = new HashMap<>();
• Display all words with their frequencies for (String word : words) {
[Link](word, [Link](word, 0) +
• Find most frequent and least frequent words 1);
}
• Demonstrate put, get, containsKey, entrySet operations
// Display
for ([Link]<String, Integer> entry :
[Link]()) {
[Link]([Link]() + ": " +
[Link]());
}
// Most frequent
String mostFrequent = "";
int maxCount = 0;
for ([Link]<String, Integer> entry :
[Link]()) {
if ([Link]() > maxCount) {
maxCount = [Link]();
Note: HashMap is ideal for counting, grouping, and lookup operations
mostFrequent = [Link]();
}
}
[Link]("Most frequent: " + mostFrequent + " ("
Experiment 3.8: Comparator & Comparable - Multi-Criteria Sorting
Java Code
// Multi-criteria
Comparator<Employee> bySalaryThenName = Comparator
.comparingDouble((Employee e) -> [Link]).reversed()
.thenComparing(e -> [Link]);
// Usage
List<Employee> employees = new ArrayList<>();
Note: Show both Comparable (natural) and Comparator (custom) sorting
// ... add employees
[Link](employees); // by id (Comparable)
[Link](byName); // by name (Comparator)
Collections Best Practices
• Always use generics for type safety: List<String> instead of List
• Choose right implementation: ArrayList for access, LinkedList for modification
• Use HashSet for uniqueness, TreeSet for sorted uniqueness
• Use HashMap for fast lookup, TreeMap for sorted keys
• Prefer interfaces over concrete classes in declarations: List<> not ArrayList<>
• Use [Link]() for read-only views
• Use [Link]() for thread-safe wrappers
• Consider capacity for ArrayList/HashMap to avoid resizing overhead
• Use for-each for simple iteration, Iterator for removal during iteration
Note: CO3 maps to PO1, PO3, PSO1, PSO2, PSO3 (strong mapping)
Key Takeaways: Module 3
• Collections Framework provides ready-to-use data structures and algorithms
• List = ordered + duplicates (ArrayList for access, LinkedList for modification)
• Set = unique only (HashSet for speed, TreeSet for sorted, LinkedHashSet for order)
• Map = key-value pairs (HashMap for speed, TreeMap for sorted keys)
• Iterator provides safe traversal; enhanced for-loop provides simplicity
• Comparable = natural ordering (1 per class); Comparator = custom ordering (many per class)
• Generics ensure type safety and eliminate explicit casting
• Collections utility class provides sorting, searching, shuffling, and other algorithms
• Choose implementation based on operations needed (access vs modification vs ordering)
Note: Master Module 3 before proceeding to Exception Handling & I/O (Module 4)
Thank You
Questions & Discussion | Next: Module 4 - Exception Handling and I/O