Java Collection Framework
Java Collection Framework
1. java.lang.Iterable
● java.util.Collection
○ java.util.List
■ ArrayList
■ LinkedList
■ Vector
● Stack
○ java.util.Set
■ HashSet
■ LinkedHashSet
■ TreeSet
○ java.util.Queue
■ PriorityQueue
■ java.util.Deque
● ArrayDeque
● LinkedList
The List interface in Java is part of the Collections Framework and represents an ordered collection
of elements. It allows duplicate values and provides control over where each element is inserted or
accessed using an index.
1. ArrayList:
Access Time Fast (O(1)) for random access Slow (O(n)) due to traversal
Practical Implementations
ArrayList Example
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Accessing elements
System.out.println("Element at index 1: " + list.get(1));
// Iterating
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
// Removing an element
list.remove("Banana");
list.remove(index no);
System.out.println("After removal: " + list); // list as an Object (to String chlegi)
}
}
LinkedList Example
import java.util.LinkedList;
// Adding elements
list.add("Lion");
list.add("Tiger");
list.add("Elephant");
// Accessing elements
System.out.println("First Element: " + list.getFirst());
System.out.println("Last Element: " + list.getLast());
// Removing elements
list.removeFirst();
list.removeLast();
System.out.println("After removal: " + list);
}
}
Vector Example
import java.util.Vector;
// Adding elements
vector.add(10);
vector.add(20);
vector.add(30);
// Accessing elements
System.out.println("Element at index 2: " + vector.get(2));
// Removing an element
vector.remove((Integer) 20);
System.out.println("After removal: " + vector);
}
}
Stack Example
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
// Adding elements
st.push(10);
st.push(20);
st.push(30);
st.push(40);
System.out.println(st); // [10,20,30,40]
For Loop:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Iterator:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Step 2: Sets in Java Collections
The Set interface in Java is part of the Collections Framework and represents a collection of unique
elements. It does not allow duplicate values, making it ideal for scenarios where uniqueness is
required.
1. HashSet:
○ Backed by a HashMap.
○ Unordered collection.
○ Provides constant-time performance for basic operations (add, remove, contains).
2. LinkedHashSet:
○ Subclass of HashSet.
○ Maintains insertion order.
○ Slightly slower than HashSet due to maintaining a linked list.
3. TreeSet:
Null Handling Allows one null Allows one null Does not allow null
Best Use Case Fast membership check Ordered unique data Sorted unique data
Practical Implementations
HashSet Example
import java.util.HashSet;
// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
// Display elements
System.out.println("HashSet: " + set);
// Removing an element
set.remove("Banana");
System.out.println("After removal: " + set);
}
}
LinkedHashSet Example
import java.util.LinkedHashSet;
// Adding elements
set.add("Lion");
set.add("Tiger");
set.add("Elephant");
// Removing an element
set.remove("Tiger");
System.out.println("After removal: " + set);
}
}
TreeSet Example
import java.util.TreeSet;
// Adding elements
set.add(40);
set.add(10);
set.add(30);
set.add(20);
// Removing an element
set.remove(20);
System.out.println("After removal: " + set);
}
}
Iterator:
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
The Map interface in Java is part of the Collections Framework and is used to store key-value pairs.
Each key in a Map must be unique, while the values can be duplicate. A Map is perfect when you need to
associate data (values) with unique identifiers (keys).
1. Key-Value Mapping: Useful for scenarios where you want to look up values using unique keys
(e.g., student roll numbers and marks).
2. Efficient Retrieval: Provides fast access to values based on their keys.
3. Prevents Duplicate Keys: Guarantees that each key is unique.
1. HashMap:
Duplicates Keys not allowed Keys not allowed Keys not allowed Keys not allowed
Null One null key One null key No null keys No null keys/values
Handling
Practical Implementations
HashMap Example
import java.util.HashMap;
// Accessing a value
System.out.println("Value for key 2: " + map.get(2));
// Accessing a value
System.out.println("Value for key 1: " + map.get(1));
TreeMap Example
import java.util.TreeMap;
// Accessing a value
System.out.println("Value for key 'B': " + table.get("B"));
class Student
{
private int rollNumber;
private String name;
Student()
{
}
Student(int rollNumber, String name)
{
this.rollNumber = rollNumber;
this.name = name;
}
map.put(s1.getRollNumber(), s1);
map.put(07, s2);
map.put(13, s3);
map.put(s4.getRollNumber(), s4); // roll number wise key hai no problem (override)
// iteration
for(Map.Entry<Integer, Student> entry : map.entrySet())
{
Integer key = entry.getKey();
Student s = entry.getValue();
System.out.println("Key: "+ key + " Roll Number: " + s.getRollNumber() + " Name: "+ s.getName());
}
}
}
Definition of Queue
A Queue in Java is a linear data structure that operates in a FIFO (First In, First Out) manner. This
means elements are inserted at the end (tail) and removed from the front (head). Queues are
particularly useful for scenarios like scheduling tasks, message buffering, or breadth-first search in
graphs.
The Queue interface is part of the Java Collections Framework and extends the Collection interface.
1. Order Management: Queues ensure the order of elements is preserved (FIFO).
2. Task Scheduling: Commonly used in task scheduling or handling requests in the order they
arrive.
3. Separation of Concerns: Queues abstract the details of data processing order.
offer(element Inserts an element into the queue. Returns false if the queue is
) full.
poll() Removes and returns the head of the queue, or null if the
queue is empty.
element() Retrieves the head of the queue without removing it. Throws an
exception if the queue is empty.
peek() Retrieves the head of the queue without removing it, or null if
the queue is empty.
// Adding elements
queue.add(10);
queue.add(20);
queue.add(30);
// Remove elements
System.out.println("Removed: " + queue.poll());
System.out.println("Queue after removal: " + queue);
}
}
2. PriorityQueue Example
import java.util.PriorityQueue;
3. ArrayDeque Example
import java.util.*;
// Adding elements
queue.offer("A");
queue.offer("B");
queue.offer("C");
queue.offerFirst("a");
queue.offerLast("Z");
// Remove elements
System.out.println("Removed: " + queue.poll());
System.out.println("Removed: " + queue.pollLast());
System.out.println("Queue after removal: " + queue);
}
}
Step 5: Utilities in Java Collections
The java.util.Collections class provides utility methods to operate on collections, such as sorting,
searching, reversing, and thread-safety wrappers. These utilities are static methods that work on List,
Set, and Map types, offering common operations efficiently and conveniently.
functions to manage collections of data. It includes components for data structures and algorithms, designed to
1. Containers:
● Containers are data structures that store and organize data. STL provides several types of containers,
categorized as:
Sequence Containers:
● vector: Dynamic array; supports fast random access and amortized constant-time push_back.
● list: Doubly linked list; good for insertions and deletions anywhere in the container but slower
random access.
● deque: Double-ended queue; supports efficient push and pop at both ends.
● array: Fixed-size array; offers faster access with a constant size at compile-time.
● Associative Containers (Ordered based on key):
● set: Stores unique elements in a sorted order.
● map: Stores key-value pairs with unique keys in sorted order.
● multiset: Allows duplicate elements in a sorted order.
● multimap: Allows duplicate key-value pairs in sorted order.
● Unordered Containers (Based on hash tables):
● unordered_set, unordered_map, unordered_multiset, unordered_multimap: Provide faster
access compared to associative containers but don't maintain element order.
2. Iterators:
● Iterators are used to traverse containers. They abstract away the internal structure of containers.
● Types:
● begin(): Points to the first element.
● end(): Points one past the last element.
● next(), prev(): Move iterators forward or backward.
● reverse_iterator: Iterates in reverse order.
● Iterators provide a uniform interface for working with all container types, enabling algorithms to operate
on any container.
3. Algorithms:
● STL algorithms are a set of functions that can be used on containers via iterators. These algorithms
provide commonly needed functionality like sorting, searching, and modifying data.
● Examples:
● Sorting: std::sort(), std::stable_sort()
● Searching: std::find(), std::binary_search()
● Modifying: std::reverse(), std::fill()
● Others: std::accumulate(), std::count(), std::copy()
● They operate on iterators, making them flexible for different container types.
4. Functors (Function Objects):
● Functors are objects that can be used as functions. They are used with STL algorithms for custom
behaviors like comparison or transformation.
● Example:
● std::sort(v.begin(), v.end(), std::greater<int>()) sorts a vector v in descending
order using a functor std::greater.
● Functors allow passing customized behavior into algorithms instead of using traditional function
pointers.
Advantages of STL:
● Reusability: Containers, iterators, and algorithms can be used together with minimal effort.
● Efficiency: STL algorithms are often optimized for performance, leveraging the underlying data
structures efficiently.
● Flexibility: It supports different kinds of containers and algorithms to meet various requirements.
● Type Safety: STL uses templates to ensure type safety at compile-time.
ChatGPT said:
Here are the basic methods for some common STL containers and their typical operations:
3. deque (Double-Ended Queue):
● push_back(): Adds an element at the end.
● push_front(): Adds an element at the front.
● pop_back(): Removes the last element.
● pop_front(): Removes the first element.
● size(): Returns the number of elements.
● empty(): Checks if the deque is empty.
● at(): Accesses an element with bounds checking.
● operator[]: Accesses an element without bounds checking.
● begin() / end(): Returns iterators to the first/last element.
C C++
Procedural OOPL
Mid level High level
Top-down bottom-up
32 keywords 96 keywords
No overloading overloading
Namespace concept No Namespace concept
Malloc , calloc New and delete
Extension .c .cpp or c++
Denies Ritchie 1972 Bjarne Stroustrup 1979
C++ vs java
1.Platform dependency
2.Primitive Pointer
3.Multiple Inheritance
4.Virtual keyword
5.No Distructor
6.Garbage Collection
7.Java James Gosling 1995