0% found this document useful (0 votes)
2 views42 pages

CUCS1004_Module3_Java_Collections_Framework

Module 3 of the Java Programming course covers the Java Collections Framework, including the List, Set, and Map interfaces, as well as iterators, sorting, and searching. It provides an overview of data structures like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap, detailing their characteristics and use cases. The module includes practical experiments to apply the concepts learned.

Uploaded by

Lakshmana Rowthu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views42 pages

CUCS1004_Module3_Java_Collections_Framework

Module 3 of the Java Programming course covers the Java Collections Framework, including the List, Set, and Map interfaces, as well as iterators, sorting, and searching. It provides an overview of data structures like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap, detailing their characteristics and use cases. The module includes practical experiments to apply the concepts learned.

Uploaded by

Lakshmana Rowthu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Collections Framework

Module 3: List, Set, Map, Iterators, Sorting & Searching

CUCS1004 | Java Programming | Module 3 | 15 Hours


Module 3 Overview
• Collections Framework: Unified architecture for storing and manipulating groups of objects
• List Interface: Ordered collection with duplicates (ArrayList, LinkedList)
• Set Interface: Unordered collection without duplicates (HashSet, TreeSet)
• Map Interface: Key-value pairs with unique keys (HashMap, TreeMap)
• Iterators: Traversing collections sequentially
• Enhanced For-Loop: Simplified iteration syntax
• Sorting & Searching: Comparable, Comparator, [Link](), binarySearch()
• 8 Experiments: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, Iterator, Comparator/Comparable

Note: Total Duration: 15 Hours | CO3: Apply collections (Applying Level)


01
Collections Framework Overview
Duration: 1 Hour
What is Java Collections Framework?
Java Code

• A unified architecture for representing and manipulating


// Core interfaces in [Link]
collections
import [Link].*;
• Consists of interfaces, implementations (classes), and
// Collection (root interface)
algorithms (utility methods) // ├── List (ordered, duplicates allowed)
// │ ├── ArrayList
• Located in [Link] package // │ └── LinkedList
// ├── Set (no duplicates)
• Reduces programming effort by providing data // │ ├── HashSet
structures and algorithms // │ └── TreeSet
// └── Map (key-value pairs)
• Increases performance with high-quality // ├── HashMap
implementations // └── TreeMap

• 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)

+-- Collection (interface)

+-- List (interface)

| +-- ArrayList

| +-- LinkedList

| +-- Vector

+-- Set (interface)

| +-- 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

• Ordered collection (maintains insertion order)


// List declaration
• Allows duplicate elements List<String> names = new ArrayList<>();

• Elements accessed by index (0-based) // Common operations


[Link]("Alice"); // [Alice]
• Extends Collection interface [Link]("Bob"); // [Alice, Bob]
[Link]("Alice"); // [Alice, Bob, Alice] -
• Common implementations: ArrayList, LinkedList, Vector duplicates allowed

• Key methods: get(index), set(index, element), add(index, // Index-based access


String first = [Link](0); // Alice
element), remove(index)
[Link](1, "Charlie"); // [Alice, Charlie, Alice]
[Link](2); // [Alice, Charlie]

// Size and search


int size = [Link](); // 2
boolean hasAlice = [Link]("Alice"); // true
int index = [Link]("Alice"); // 0

Note: List preserves insertion order and allows random access by index
ArrayList: Dynamic Array Implementation
Java Code

• Backed by dynamic array (resizable array)


import [Link];
• Fast random access: O(1) for get() and set()
ArrayList<String> list = new ArrayList<>();
• Slow insertion/deletion in middle: O(n) due to shifting
// Adding elements
• Initial capacity 10, grows by 50% when full [Link]("Java");
[Link]("Python");
• Not synchronized (not thread-safe) [Link](1, "C++"); // insert at index 1

• Better for frequent access, less modification // Accessing


String lang = [Link](0); // Java

// Updating
[Link](2, "JavaScript");

// Removing
[Link]("C++"); // by object
[Link](0); // by index

// Iterating
for (String s : list) {
[Link](s);
}

Note: Use ArrayList when read operations dominate; default capacity = 10


// Size
[Link]([Link]());
LinkedList: Doubly-Linked List Implementation
Java Code

• Backed by doubly-linked list (each node has prev and


import [Link];
next reference)
LinkedList<String> list = new LinkedList<>();
• Fast insertion/deletion at ends: O(1)
// Adding at both ends
• Slow random access: O(n) must traverse from head
[Link]("First");
[Link]("Last");
• Implements both List and Deque interfaces
[Link]("Middle");
• Can be used as stack (LIFO) or queue (FIFO)
// Deque operations
[Link]("Queued"); // add to tail
• Better for frequent modification, less access
[Link](); // remove from head
[Link](); // view head without removing

// Stack operations (LIFO)


[Link]("Pushed"); // add to head
[Link](); // remove from head

// Removing from ends


[Link]();
[Link]();

// Iterating
Iterator<String> it = [Link]();
Note: LinkedList implements List, Deque, and Queue interfaces
while ([Link]()) {
[Link]([Link]());
}
ArrayList vs LinkedList Comparison
Operation ArrayList LinkedList

get(index) O(1) - Fast O(n) - Slow

add(end) O(1) amortized O(1)

add(middle) O(n) - shifts elements O(n) - finds position

remove(middle) O(n) - shifts elements O(n) - finds position

add/remove(ends) O(n) O(1) - Fast

Memory overhead Low (only data) High (prev+next pointers)

Use case Frequent access Frequent modification

Thread-safe No No
03
Set Interface
Duration: 2 Hours
Set Interface: Unique Elements Collection
Java Code

• Collection that cannot contain duplicate elements


// Set declaration
• No guaranteed order (except LinkedHashSet and Set<String> names = new HashSet<>();
TreeSet)
// Adding elements
[Link]("Alice");
• Uses equals() and hashCode() to check duplicates
[Link]("Bob");
[Link]("Alice"); // duplicate - ignored
• Extends Collection interface
[Link](names); // [Alice, Bob] - no duplicates
• Common implementations: HashSet, LinkedHashSet,
TreeSet // Checking membership
boolean hasAlice = [Link]("Alice"); // true
• Key methods: add(), remove(), contains(), size(),
isEmpty() // Removing
[Link]("Bob");

// Size
int size = [Link](); // 1

// Iterating (order not guaranteed)


for (String name : names) {
[Link](name);
}

Note: Set is ideal for removing duplicates from a collection


HashSet: Hash Table Implementation
Java Code

• Backed by HashMap (hash table with dummy values)


import [Link];
• No guaranteed order of elements
HashSet<Integer> numbers = new HashSet<>();
• Fast operations: O(1) for add, remove, contains
// Adding elements
• Allows null element (only one, since no duplicates) [Link](10);
[Link](20);
• Not synchronized (not thread-safe) [Link](30);
[Link](20); // duplicate - ignored
• Uses hashCode() for bucketing, equals() for equality
[Link](numbers); // [20, 10, 30] - unordered
check
// Bulk operations
HashSet<Integer> set2 = new HashSet<>();
[Link](20);
[Link](40);

// 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

• Backed by Red-Black Tree (self-balancing BST)


import [Link];
• Elements stored in sorted (natural) order
TreeSet<Integer> sorted = new TreeSet<>();
• Slower than HashSet: O(log n) for add, remove, contains
// Adding elements (auto-sorted)
• No null elements allowed (cannot compare null) [Link](30);
[Link](10);
• Implements NavigableSet interface (sorted set [Link](20);
[Link](50);
operations)
[Link](40);
• Elements must implement Comparable or provide
[Link](sorted); // [10, 20, 30, 40, 50]
Comparator
// NavigableSet operations
Integer first = [Link](); // 10
Integer last = [Link](); // 50

Integer higher = [Link](25); // 30 (strictly


greater)
Integer lower = [Link](25); // 20 (strictly less)

Integer ceiling = [Link](25); // 30 (>= 25)


Integer floor = [Link](25); // 20 (<= 25)

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

Ordering None Sorted (natural) Insertion order

Underlying Hash table Red-Black Tree Hash table + Linked list

add/remove/contains O(1) O(log n) O(1)

null allowed Yes (one) No Yes (one)

Comparator Not needed Required or Comparable Not needed

Memory Low Higher Higher

Use case Fast unique set Sorted unique set Ordered unique set
04
Map Interface
Duration: 3 Hours
Map Interface: Key-Value Pairs
Java Code

• Stores data as key-value pairs (entries)


// Map declaration
• Keys are unique (no duplicates), values can be duplicated Map<String, Integer> scores = new HashMap<>();

• Each key maps to exactly one value // Adding entries


[Link]("Alice", 85);
• Does NOT extend Collection interface (separate [Link]("Bob", 90);
[Link]("Charlie", 78);
hierarchy)
// Duplicate key - overwrites value
• Common implementations: HashMap, LinkedHashMap,
[Link]("Alice", 95);
TreeMap
// Accessing by key
• Key methods: put(), get(), remove(), containsKey(), Integer aliceScore = [Link]("Alice"); // 95
containsValue(), keySet(), values()
// Checking
boolean hasKey = [Link]("Bob"); // true
boolean hasValue = [Link](100); // false

// Removing
[Link]("Charlie");

// Size
int size = [Link](); // 2

Note: Map is perfect for lookup tables, caches, counting occurrences


// Iterating over entries
for ([Link]<String, Integer> entry : [Link]())
{
[Link]([Link]() + ": " +
HashMap: Hash Table Based Map
Java Code

• Backed by array of buckets (hash table with linked


import [Link];
lists/trees)
HashMap<String, String> capitals = new HashMap<>();
• No guaranteed order of entries
// Adding entries
• Fast operations: O(1) for put, get, remove (average case)
[Link]("India", "New Delhi");
[Link]("USA", "Washington DC");
• Allows one null key and multiple null values
[Link]("UK", "London");
• Not synchronized (not thread-safe)
// Accessing
String indiaCapital = [Link]("India");
• Java 8+: buckets convert to tree when collisions exceed
threshold // Check and default
String japan = [Link]("Japan", "Unknown");

// Put if absent
[Link]("India", "Mumbai"); // won't
overwrite

// Replace
[Link]("UK", "London", "Manchester");

// Remove with condition


[Link]("USA", "Washington DC");
Note: HashMap is most commonly used Map implementation for general purposes
// Iterate keys
for (String country : [Link]()) {
[Link](country);
TreeMap: Sorted Map Implementation
Java Code

• Backed by Red-Black Tree (self-balancing BST)


import [Link];
• Entries sorted by keys (natural order or custom
TreeMap<String, Integer> grades = new TreeMap<>();
Comparator)
// Adding entries (auto-sorted by key)
• Slower than HashMap: O(log n) for put, get, remove
[Link]("Charlie", 85);
[Link]("Alice", 92);
• No null keys allowed (cannot compare null)
[Link]("Bob", 78);
• Implements NavigableMap interface (sorted map
[Link](grades);
operations) // {Alice=92, Bob=78, Charlie=85} - sorted by key

• Keys must implement Comparable or provide // NavigableMap operations


Comparator String first = [Link](); // Alice
String last = [Link](); // Charlie

String higher = [Link]("Bob"); // Charlie


String lower = [Link]("Bob"); // Alice

// 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

Key Ordering None Sorted (natural) Insertion order

Underlying Hash table Red-Black Tree Hash table + Linked list

put/get/remove O(1) O(log n) O(1)

null key Yes (one) No Yes (one)

null values Yes Yes Yes

Comparator Not needed Required or Comparable Not needed

Use case Fast lookup Sorted keys/range queries Ordered cache


05
Iterators & Enhanced For-Loop
Duration: 2 Hours
Iterator: Universal Collection Traversal
Java Code

• Iterator provides uniform way to traverse any Collection


import [Link];
• Three core methods: hasNext(), next(), remove()
List<String> names = new ArrayList<>();
• Obtained via [Link]() method [Link]("Alice");
[Link]("Bob");
• Fail-fast: throws ConcurrentModificationException if [Link]("Charlie");
collection modified during iteration
// Using Iterator
Iterator<String> it = [Link]();
• ListIterator (for Lists only): supports bidirectional
while ([Link]()) {
traversal and modification String name = [Link]();
[Link](name);
• Enhanced for-loop (for-each) uses Iterator internally
// Safe removal during iteration
if ([Link]("Bob")) {
[Link](); // removes current element
}
}

// ListIterator (bidirectional, for Lists only)


ListIterator<String> lit = [Link]();
while ([Link]()) {
[Link]([Link]());
}
Note: Always use [Link]() instead of [Link]() during iteration
while ([Link]()) {
[Link]([Link]()); // reverse!
}
Enhanced For-Loop: Simplified Iteration
Java Code

• Syntactic sugar for iterating over arrays and collections


// Enhanced for-loop with List
• Syntax: for (Type element : collection) { body } List<String> fruits = [Link]("Apple", "Banana",
"Cherry");
• Cannot modify collection during iteration for (String fruit : fruits) {
[Link](fruit);
(ConcurrentModificationException)
}
• Cannot access index (use traditional for-loop if index
// With arrays
needed) int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
• Cannot iterate backwards [Link](num);
}
• Internally uses Iterator (compiled to iterator-based code)
// With Set
Set<Integer> unique = new HashSet<>();
[Link](1); [Link](2); [Link](3);
for (int val : unique) {
[Link](val);
}

// With Map (entrySet)


Map<String, Integer> map = new HashMap<>();
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " = " +
Note: For-each is clean and readable but limited for complex iteration needs
[Link]());
}

// With Map (keySet)


Iterator vs For-Each vs Traditional For-Loop
Feature Iterator Enhanced For-Loop Traditional For-Loop

Syntax complexity Moderate Simple Moderate

Remove during iteration Yes ([Link]()) No No (unless using iterator)

Access index No No Yes

Iterate backwards ListIterator only No Yes

Modify elements Yes (ListIterator) No Yes (by index)

Works with all collections Yes Yes Lists only

Works with arrays No Yes Yes


06
Sorting & Searching
Duration: 2 Hours
Comparable: Natural Ordering
Java Code

• Comparable interface defines natural ordering of objects


import [Link];
• Single method: compareTo(Object o) returns int
class Student implements Comparable<Student> {
• Returns negative: this < other, zero: this == other, int id;
String name;
positive: this > other
double marks;
• Class implements Comparable to define its natural sort
// Natural ordering: by marks (descending)
order @Override
public int compareTo(Student other) {
• String, Integer, Double and other wrapper classes // Descending order
implement Comparable if ([Link] > [Link]) return -1;
if ([Link] < [Link]) return 1;
• Only one natural ordering per class return 0;

// 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));

[Link](students); // uses compareTo()


// Sorted by marks descending: Bob(92), Alice(85),
Comparator: Custom Ordering
Java Code

• Comparator defines external/custom ordering (multiple


import [Link];
per class)
// Anonymous inner class (old way)
• Single method: compare(Object o1, Object o2) returns
Comparator<Student> byName = new Comparator<Student>() {
int @Override
public int compare(Student s1, Student s2) {
• Can sort by different criteria without modifying class return [Link]([Link]);
}
• Java 8+: lambda expressions and method references for };
concise comparators
// Lambda expression (Java 8+)
• Static methods: [Link](), Comparator<Student> byId = (s1, s2) ->
[Link]() [Link]([Link], [Link]);

• Chaining: thenComparing() for multi-level sorting // Method reference


Comparator<Student> byNameRef = [Link](s ->
[Link]);

// 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

• [Link](list): Sorts list in natural order (uses


import [Link];
Comparable)
List<Integer> nums = new ArrayList<>([Link](5, 2, 8,
• [Link](list, comparator): Sorts with custom
1, 9, 3));
comparator
// Sorting
• [Link](list, key): Fast search in sorted [Link](nums); // [1, 2, 3, 5, 8, 9]
list (O(log n))
// Binary search (list must be sorted)
• [Link](list): Reverses element order int index = [Link](nums, 5); // 3

• [Link](list): Randomizes element order // Reverse


[Link](nums); // [9, 8, 5, 3, 2, 1]
• [Link](list) / [Link](list): Finds
extremes // Shuffle
[Link](nums);
• [Link](list, obj): Replaces all elements
// Max and Min
• [Link](dest, src): Copies elements from source Integer max = [Link](nums);
to destination Integer min = [Link](nums);

• [Link](list, i, j): Swaps elements at indices // Frequency


int count = [Link](nums, 5);
• [Link](list, obj): Counts occurrences
Note: Collections class provides algorithms that work on any Collection implementation
// Fill
[Link](nums, 0); // [0, 0, 0, 0, 0, 0]

// Unmodifiable list
07
Generics with Collections
Duration: 1 Hour
Generics: Type-Safe Collections
Java Code

• Generics enable type-safe collections (compile-time type


// Without generics (raw type - NOT recommended)
checking)
List rawList = new ArrayList();
[Link]("Hello");
• Syntax: Collection<Type> (e.g., List<String>,
[Link](123); // compiles but risky!
Map<Integer, String>) String s = (String) [Link](0); // explicit cast
needed
• Eliminates ClassCastException at runtime
// With generics (type-safe)
• No need for explicit casting when retrieving elements List<String> names = new ArrayList<>();
[Link]("Alice");
• Diamond operator <> (Java 7+): infers type from // [Link](123); // COMPILE ERROR! Type safety
declaration String name = [Link](0); // no cast needed

• Generic types: E (Element), K (Key), V (Value), T (Type), N // Generic Map


(Number) Map<String, Integer> scores = new HashMap<>();
[Link]("Alice", 95);

// Diamond operator (Java 7+)


List<Integer> numbers = new ArrayList<>(); // type
inferred

// 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

• Unbounded wildcard (?): Any type (read-only


// Unbounded wildcard (read-only)
operations)
public void printAny(List<?> list) {
for (Object obj : list) {
• Upper bounded wildcard (? extends T): T or subclass of T
[Link](obj);
}
• Lower bounded wildcard (? super T): T or superclass of T
}
• PECS principle: Producer Extends, Consumer Super
// Upper bounded (Number or subclass)
public double sum(List<? extends Number> list) {
• Use extends when reading from collection (producing)
double total = 0;
for (Number n : list) {
• Use super when writing to collection (consuming)
total += [Link]();
}
return total;
}
// Works with: List<Integer>, List<Double>, List<Float>

// Lower bounded (Integer or superclass)


public void addIntegers(List<? super Integer> list) {
[Link](10);
[Link](20);
}
// Works with: List<Integer>, List<Number>, List<Object>

Note: Wildcards add flexibility while maintaining type safety


// PECS example
public void copy(List<? extends Number> src, List<? super
Number> dest) {
for (Number n : src) {
08
Syllabus Experiments
Duration: Practical
Module 3: Syllabus Experiments (8 Experiments)
• Experiment 3.1: ArrayList - CRUD operations, searching, sorting student records
• Experiment 3.2: LinkedList - Implement stack and queue operations
• Experiment 3.3: HashSet - Remove duplicates, union, intersection, difference
• Experiment 3.4: TreeSet - Store and retrieve sorted unique elements, range queries
• Experiment 3.5: HashMap - Phone book, word frequency counter, student grades
• Experiment 3.6: TreeMap - Sorted dictionary, range-based queries
• Experiment 3.7: Iterator - Forward/backward traversal, safe removal during iteration
• Experiment 3.8: Comparator & Comparable - Multi-criteria sorting of custom objects

Note: Each experiment: Problem statement, expected output, code, and conclusion
Experiment 3.1: ArrayList - Student Management
Java Code

• Create Student class with id, name, marks, department


class Student implements Comparable<Student> {
• Use ArrayList to store multiple Student objects int id; String name; double marks;
public int compareTo(Student s) {
• Implement add, remove, update, display operations return [Link]([Link], [Link]);
}
• Search student by id or name }

• Sort students by marks using Comparable ArrayList<Student> students = new ArrayList<>();


[Link](new Student(1, "Alice", 85));
• Find top performer and average marks [Link](new Student(2, "Bob", 92));

// 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

• Read a paragraph of text from user


String text = "java is great java is powerful";
• Split into words and count frequency of each word String[] words = [Link]().split(" \s+");

• 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

• Create Employee class with id, name, salary,


class Employee implements Comparable<Employee> {
department, joiningDate
int id; String name; double salary;
LocalDate joiningDate;
• Implement Comparable for natural ordering (by id)
public int compareTo(Employee e) {
• Create multiple Comparators: byName, bySalary, byDate
return [Link]([Link], [Link]);
}
• Sort employee list using different criteria
}
• Demonstrate chained comparators (salary then name)
// Comparators
Comparator<Employee> byName = [Link](e ->
• Use lambda expressions and method references
[Link]);
Comparator<Employee> bySalary = Comparator
.comparingDouble(e -> [Link]).reversed();
Comparator<Employee> byDate = [Link](e ->
[Link]);

// 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: Proper collection choice significantly impacts performance and memory


Common Mistakes to Avoid
• Modifying collection during for-each iteration (ConcurrentModificationException)
• Using raw types without generics (ClassCastException at runtime)
• Using == instead of equals() for object comparison in contains()/remove()
• Forgetting to implement equals() and hashCode() for custom objects in HashSet/HashMap
• Assuming HashSet/HashMap maintains insertion order (use LinkedHashXxx instead)
• Using TreeSet/TreeMap with non-Comparable objects without Comparator
• Not checking containsKey() before get() (null vs missing key ambiguity)
• Using index-based access on LinkedList (O(n) instead of O(1))

Note: Understanding these pitfalls saves hours of debugging time


Module 3: Course Outcomes (CO3)
• CO3: Apply collections, exception handling, and file I/O operations in Java (Applying Level)
• Select appropriate Collection implementation based on requirements
• Implement List operations: ArrayList and LinkedList for ordered data
• Implement Set operations: HashSet and TreeSet for unique data
• Implement Map operations: HashMap and TreeMap for key-value pairs
• Traverse collections using Iterator and enhanced for-loop
• Sort collections using Comparable (natural order) and Comparator (custom order)
• Search collections efficiently using [Link]()
• Apply generics for type-safe collection usage

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

CUCS1004 | Java Programming | Module 3 | 15 Hours

You might also like