Java Module-4
Java Module-4
COLLECTION FRAMEWORK
Collection Framework: Collections Overview, Collection Interfaces - List, Set, Map, List -
ArrayList, Linked List, Vector, Set - HashSet, TreeSet, Map - HashTable, HashMap,
Accessing a collection via an Iterator, comparator, comparable.
Collection:
A Collection in Java is a framework that provides an architecture to store and
manipulate a group of objects efficiently. It includes interfaces (List, Set, Queue) and their
implementations (ArrayList, HashSet, LinkedList, etc.) to manage data dynamically.
Collection Overview:
The Java Collection Framework is a set of interfaces, classes, and methods that
provide an efficient way to store, manipulate, and process groups of objects in Java. It
includes Lists, Sets, Queues, and Maps, each designed for different use cases.
Key Roles of Collections:
Stores Multiple Objects – Unlike arrays, collections dynamically manage data.
Provides Efficient Data Handling – Sorting, searching, insertion, and deletion are
optimized.
Supports Different Data Structures – Includes Lists, Sets, Queues, and Maps.
Uses Generics for Type Safety – Prevents runtime type errors (List<String> list = new
ArrayList<>();).
Uses Utility Methods – The Collections class offers sorting, shuffling, and searching.
Collection (Interface)
Definition:
It is the root interface of the Java Collection Framework (except for Map).
Provides basic methods to add, remove, and manipulate objects.
Subinterfaces: List, Set, Queue.
Key Role:
Defines basic CRUD operations (Create, Read, Update, Delete).
Provides methods like add(), remove(), contains(), size(), etc.
Syntax:
Collectioninterface<Type> object = new Classimplementation<>(); or
classimplementation<Type> object=new Classimplementation <>();
Example Implementation:
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
Collection<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println("Fruits: " + fruits); // [Apple, Banana]
fruits.remove("Apple");
System.out.println("After removal: " + fruits); // [Banana]
}
}
Example Implementation:
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
Collections.sort(numbers); // Sorts the list
System.out.println("Sorted: " + numbers); // [1, 2, 5, 8]
Collections.reverse(numbers); // Reverses order
System.out.println("Reversed: " + numbers); // [8, 5, 2, 1]
}
}
3️. Collection Framework
Definition:
A set of interfaces and classes that provides an architecture for storing and
manipulating groups of objects efficiently.
Includes List, Set, Queue, and Map.
Key Role:
Provides built-in data structures and algorithms for managing collections.
Components in Collection Framework:
Example:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("ArrayList: " + list);
list.remove("Banana");
System.out.println("After removal: " + list);
}
}
Output:
ArrayList: [Apple, Banana, Cherry]
After removal: [Apple, Cherry]
2. LinkedList:
A LinkedList is a doubly linked list allowing fast insertions and deletions but slower random
access.
Method Description
addFirst(E e) Adds an element to the beginning.
addLast(E e) Adds an element to the end.
removeFirst() Removes the first element.
removeLast() Removes the last element.
getFirst() Returns the first element.
getLast() Returns the last element.
Example:
import java.util.LinkedList;
public class LinkedListExample {s
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(10);
list.add(20);
list.add(30);
3. Vector:
A Vector is similar to an ArrayList but is synchronized (thread-safe).
Synchronized (Thread-safe),
Slower performance
Example:
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<Double> vector = new Vector<>();
vector.add(1.1);
vector.add(2.2);
vector.add(3.3);
System.out.println("Vector: " + vector);
vector.remove(1); // Removes the second element
System.out.println("After removal: " + vector);
}
}
Output:
Vector: [1.1, 2.2, 3.3]
After removal: [1.1, 3.3]
4. Stack:
Extends Vector, A Stack follows the LIFO (Last In, First Out) principle.
Method Description
push(E item) Adds an element to the top of the stack (preferred over add()).
pop() Removes and returns the top element.
peek() Returns the top element without removing it.
isEmpty() Checks if the stack is empty.
search(E item) Returns the position (1-based index) of an item.
add(E item) Works like push(), but not recommended.
remove(E item) Works but not recommended because Stack is LIFO.
Example:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("First");
stack.push("Second");
stack.push("Third");
System.out.println("Stack: " + stack);
System.out.println("Popped: " + stack.pop());
System.out.println("After pop: " + stack);
System.out.println("Peek: " + stack.peek()); // Check top element
}
}
Output:
Stack: [First, Second, Third]
Popped: Third
After pop: [First, Second]
Peek: Second
2️. Set (No Duplicates, No Order):
A Set in Java is a part of the Collection Framework that represents a collection of
unique elements. It does not allow duplicate values and is mainly implemented using
HashSet, LinkedHashSet, and TreeSet.
Features:
1. HashSet Example
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate, will not be added
// Displaying set
System.out.println("HashSet: " + set);
// Removing an element
set.remove("Cherry");
Output:
2. LinkedHashSet Example
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(10);
set.add(20);
set.add(30);
set.add(10); // Duplicate, ignored
Output:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(50);
set.add(10);
set.add(30);
set.add(20);
Output:
import java.util.Set;
import java.util.HashSet;
Output:
Union: [A, B, C, D]
Intersection: [B, C]
Difference: [A]
import java.util.LinkedList;
import java.util.Queue;
public class LinkedListQueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// Adding elements
queue.add("Alice");
queue.offer("Bob");
queue.offer("Charlie");
// Retrieving elements
System.out.println("Head: " + queue.peek());
// Removing elements
queue.poll(); // Removes "Alice"
System.out.println("Queue after poll: " + queue);
}
}
Output:
2. PriorityQueue Example
Sorted order (natural order or custom comparator).
Does not allow null values.
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(10);
pq.add(20);
Output:
import java.util.ArrayDeque;
import java.util.Queue;
public class ArrayDequeExample {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
queue.offer("One");
queue.offer("Two");
queue.offer("Three");
import java.util.LinkedList;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
// Adding elements
queue.offer(5);
queue.offer(10);
queue.offer(15);
// Removing elements
queue.poll();
System.out.println("Queue after poll: " + queue);
// Checking size
System.out.println("Queue size: " + queue.size());
}
}
Output:
// Retrieving values
System.out.println("Value for key 2: " + map.get(2));
// Iterating over a map
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// Removing an entry
map.remove(1);
System.out.println("After removal: " + map);
}
}
Output:
Value for key 2: Banana
Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Cherry
Contains key 3? true
After removal: {2=Banana, 3=Cherry}
2. LinkedHashMap Example:
Maintains insertion order.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("John", 25);
map.put("Alice", 30);
map.put("Bob", 22);
3. TreeMap Example
Sorted order based on keys.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(100, "A");
map.put(50, "B");
map.put(150, "C");
// Updating a value
scores.put("English", 88);
System.out.println("Updated Scores: " + scores);
}
}
Output:
Scores: {Math=90, English=85, Science=92}
Contains Science? true
Subjects: [Math, English, Science]
Marks: [90, 85, 92]
Updated Scores: {Math=90, English=88, Science=92}
Iterator in Java
An Iterator in Java is an interface in the java.util package that provides a way to
traverse elements of a collection one by one without exposing its underlying structure. It is
mainly used with Collection Framework classes like ArrayList, HashSet, LinkedList, etc.
Syntax
Iterator<Type> iterator = collection.iterator();
Methods of Iterator:
Method Description
boolean hasNext() Returns true if the iteration has more elements.
Type next() Returns the next element in the iteration.
void remove() Removes the last element returned by next(). (Optional operation)
import java.util.*;
class Employee implements Comparable<Employee> {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
// Sorting by ID (Natural Order)
@Override
public int compareTo(Employee other) {
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
}
public class ComparableExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(103, "Alice", 50000));
employees.add(new Employee(101, "Bob", 70000));
employees.add(new Employee(102, "Charlie", 60000));
Sorted by ID:
[ID: 101, Name: Bob, Salary: 70000.0, ID: 102, Name: Charlie, Salary: 60000.0, ID: 103,
Name: Alice, Salary: 50000.0]
import java.util.*;
// Employee class without Comparable
class Employee {
int id;
String name;
double salary;
@Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
}
// Sorting by Name
employees.sort(new NameComparator());
System.out.println("Sorted by Name:\n" + employees);
// Sorting by Salary
employees.sort(new SalaryComparator());
System.out.println("\nSorted by Salary:\n" + employees);
}
}
Output
Sorted by Name:
[ID: 103, Name: Alice, Salary: 50000.0, ID: 101, Name: Bob, Salary: 70000.0, ID: 102,
Name: Charlie, Salary: 60000.0]
Sorted by Salary:
[ID: 103, Name: Alice, Salary: 50000.0, ID: 102, Name: Charlie, Salary: 60000.0, ID: 101,
Name: Bob, Salary: 70000.0]
import java.util.*;
class Employee {
int id;
String name;
double salary;
[ID: 101, Name: Alice, Salary: 50000.0, ID: 102, Name: Bob, Salary: 60000.0]