0% found this document useful (0 votes)
3 views49 pages

Collection Framework

The Collection Framework in Java provides a unified architecture for storing and manipulating groups of objects, enabling efficient data storage, search, and manipulation. It includes various data structures such as ArrayList, LinkedList, Stack, and HashMap, each with specific use cases and advantages. The framework also supports generics for type safety and offers methods for sorting and iterating through collections.

Uploaded by

mamabisoi71
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)
3 views49 pages

Collection Framework

The Collection Framework in Java provides a unified architecture for storing and manipulating groups of objects, enabling efficient data storage, search, and manipulation. It includes various data structures such as ArrayList, LinkedList, Stack, and HashMap, each with specific use cases and advantages. The framework also supports generics for type safety and offers methods for sorting and iterating through collections.

Uploaded by

mamabisoi71
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

Collection Framework

Why Collection Framework?

✓ Storing and Manipulating Data in Web Applications


❑ When you query a database for a list of users.
✓ Efficient Storage and Search of Key-Value Pairs
❑ Transferring data to front-end application
✓ Storing Unique Data
❑ A class attendance system needs to ensure that each student can
only be marked once.
✓ Sorting Data
❑ You want to sort a list of books based on their price.
What is Collection Framework?

✓ A collection is an object that represents a group of objects.


✓ The Java Collection Framework is a set of classes and interfaces in
Java that provide a unified architecture for storing and manipulating a
group of objects.
✓ The collection interfaces are divided into two groups.
✓ [Link] Collection Map

✓ [Link]
SortedMap
Set List

SortedSet
Application of Major Components

✓ ArrayList: Used to store dynamically sized lists of elements, ideal for


when frequent access to elements by index is required.
✓ LinkedList: Used for implementing linked lists, useful when there are
frequent insertions and deletions in a list.
✓ Vector: A growable array of objects, typically used in legacy code,
but now replaced by ArrayList for most use cases. (thread safe)
✓ Stack: Implements a last-in, first-out (LIFO) stack, useful for operations
like undo-redo or parsing expressions.
Application of Major Components

✓ Queue: Represents a collection designed for holding elements in a


FIFO (First-In-First-Out) order, useful for managing tasks in order of
arrival.
✓ Deque: A linear collection that supports element insertion and
removal at both ends.
✓ PriorityQueue: A queue where elements are dequeued based on
priority rather than the order they were added, typically used in
scheduling or sorting tasks.
Application of Major Components

✓ Set: It is an unordered collection of objects in which duplicate values


cannot be stored
✓ HashSet: Stores unique elements with no particular order, great for
eliminating duplicates.
✓ TreeSet: A Set implementation that stores elements in a sorted order, useful
when you need sorted collections with no duplicates.
✓ HashMap: Implements a key-value map with no duplicate keys, useful for
storing and retrieving elements based on a unique key.
✓ TreeMap: A Map that stores key-value pairs in a sorted order based on the
key, useful when sorting entries by key.
Advantages of Collection Framework

REDUCES
DYNAMIC DATA UNIFIED INCREASES
PROGRAMMING
SIZING INTEGRITY ARCHITECTURE PROGRAM SPEED
EFFORT
AND QUALITY

Unlike arrays, collections The collection framework It allows them to


like ArrayList and provides a single, concentrate on the core
Reduces programming Collections like HashSet
LinkedList can dynamically consistent interface for business logic of their
effort by providing and TreeSet
resize, allowing flexibility in data structures like lists, applications rather than
data structures and automatically prevent
managing data without sets, queues, and maps, on implementing generic
algorithms so you don't duplicate entries,
worrying about fixed size simplifying programming collection functionalities,
have to write them ensuring data integrity
limitations. and code readability. thus speeding up the
yourself. without extra code.
development process.
Collection Interface
public interface Collection {
✓ The Collection interface is the root of the int size();
collection hierarchy boolean isEmpty();
boolean contains(Object element);
✓ JDK doesn't provide any direct boolean add(Object element);
boolean remove(Object element);
implementations of this interface Iterator iterator();

✓ It provides implementations of more specific boolean containsAll(Collection c);


boolean addAll(Collection c);
sub interfaces like Set and List boolean removeAll(Collection c);
boolean retainAll(Collection c);
✓ Some Collection implementations allow - void clear();
o duplicate elements and others do not
Object[] toArray();
o the elements to be ordered or not Object[] toArray(Object a[]);
}
ArrayList
Collection

✓ ArrayList is a class that is part of the Java Collections


Framework. List

✓ It is a resizable array implementation of the List interface.


AbstractList
✓ It can grow or shrink in size as needed, unlike regular arrays
in Java, which have a fixed size.
ArrayList
✓ ArrayLists come from the [Link] package

Constructor Description
ArrayList() build an empty array list.
ArrayList(Collection c) build an array list with the elements of the collection.
ArrayList(int capacity) build an array list that has the specified initial capacity.
Characteristics of ArrayList

✓ Resizable: ArrayList automatically grows as elements are added. There is no fixed size,
unlike arrays.
✓ Ordered: Elements in an ArrayList are stored in the order in which they are inserted. It
maintains the insertion order.
✓ Index-based Access: Elements can be accessed via indices (positions in the list),
similar to arrays.
✓ Allows Duplicate Elements: ArrayList allows duplicate elements.
✓ Allows Null Values: You can store null values in an ArrayList.
✓ Not Synchronized: ArrayList is not synchronized, if multiple threads access it
simultaneously.
Methods of ArrayList
Method Description
add(E e) Adds an element to the end of the list.
add(int index, E element) Inserts an element at a specific index.
get(int index) Retrieves the element at the specified index.
remove(int index) Removes the element at the specified index.
size() Returns the number of elements in the list.
isEmpty() Checks if the list is empty.
contains(Object o) Checks if the list contains the specified element.
clear() Removes all elements from the list.
set(int index, E element) Replaces the element at the specified index with a new element.
indexOf(Object o) Returns the index of the first occurrence of the specified element.
boolean addAll(Collection c) Appends all of the elements from the collection to the end of this
list
Iterate an ArrayList
for-each loop
for(Object fruit: list){
ArrayList list = new ArrayList(); [Link]((String)fruit+" ");
}
[Link]("Apple");
[Link]("Banana");
forEach Method (Java 8+)
[Link]("Orange");
[Link]("Mango");
[Link](fruit -> [Link](fruit));

Iterator ([Link])
for loop Iterator iterator = [Link]();
for (int i = 0; i < [Link](); i++) { while ([Link]()) {
[Link]([Link](i)); [Link]([Link]());
} }
ArrayList Example // Removing element from ArrayList
// Remove Orange
Iterator itr = [Link]();
while([Link]()){
import [Link]; String fruit = (String) [Link]();
if([Link]("Orange")){
public class ArrayListExample { [Link]();
public static void main(String[] args) { }
}
// Creating an ArrayList [Link]("ArrayList after remove:");
ArrayList list = new ArrayList(); for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
// Adding elements to the ArrayList }
[Link]("Apple");
[Link]("Banana"); }
[Link]("Orange"); } Note: The Iterator's remove() method is
[Link]("Mango"); designed to safely remove elements
// Displaying the ArrayList elements during iteration, while direct remove
[Link]("ArrayList elements:"); using remove(), can disrupt the iteration
for (int i = 0; i < [Link](); i++) { process and generate
[Link]([Link](i)); ConcurrentModificationException.
}
Sort ArrayList

✓ The [Link] package provides a utility class Collections, which has


the static method sort().

import [Link].*; //Sorting the list


class SortArrayList{ [Link](list1);
public static void main(String args[]){
//Creating a list of fruits for(String fruit:list1)
ArrayList list1=new ArrayList(); [Link](fruit);
[Link]("Mango"); }
[Link]("Apple"); }
[Link]("Banana");
[Link]("Grapes");
Comparator Interface
✓ Java Comparator interface is used to order the objects of a user-defined class.
✓ This interface is found in [Link] package and contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
✓ It provides multiple sorting sequences, i.e., you can sort the elements on the basis of
any data member, for example, rollno, name, age or anything else.

public int compare(Object o1, Object o2): It is used to compare the current object with
the specified object. It returns -
• A negative integer if o1 should come before o2.
• A positive integer if o1 should come after o2.
• Zero if both are considered equal in terms of sorting order.
Sort ArrayList using Comparator

import [Link].*; // Comparator


class Student{ class CustomComparator implements Comparator<Student>{
String name; @Override
double cgpa; public int compare(Student s1, Student s2){
Student(int roll, String name, double cgpa){ // for integer field;
[Link] = roll; // return [Link] – [Link]
[Link] = name; // for double filed
[Link] = cgpa; // return [Link]([Link], [Link]);
} // for String filed
void display(){ return [Link]([Link]);
[Link](roll+” ”+name+" "+cgpa); }
} }
}
Sort ArrayList using Comparator
class StudentList{
public static void main(String[] args){
ArrayList<Student> students = new ArrayList<>();

[Link](new Student(5, "A", 9.2));


[Link](new Student(2, "D", 8.2));
[Link](new Student(4, "E", 6.2));
[Link](new Student(1, "C", 9.1));
[Link](new Student(3, "B", 8.8));

[Link](students, new CustomComparator());

for(Student s: students){
[Link]();
}
}
}
Array vs ArrayList
Feature Array ArrayList
Fixed size. Once defined, cannot Dynamic size. Can grow or shrink as
Size be changed. needed.
Can store elements of only one Can store objects of any type
Type type (homogeneous). (heterogeneous), but typically used
with generics.
Memory is allocated at once. Memory is dynamically managed,
Memory increasing as needed.
Slightly faster for primitive types Slightly slower due to overhead
Performance due to direct memory allocation. (dynamic resizing, object storage,
etc.).
Storage Type Can store primitive types Can only store objects
Can contain null values only for Can store null values, even for
Null Values reference types. reference types.
Adding/Removing Cannot add or remove elements Supports adding, removing, and
Elements dynamically. modifying elements dynamically.
Generics

✓ Generics in Java are a mechanism that allows you to define classes, interfaces, and
methods with a placeholder for types.
✓ This provides stronger type checking at compile-time and allows code to be more
reusable and type-safe.
✓ The main idea behind generics is to provide a way to specify the types of objects a
class or method will work with, rather than using raw types.
✓ With generics, you specify the type of object the collection will hold (e.g.,
ArrayList<String> list = new ArrayList<>();) and the compiler ensures that only objects of
that type are added.
Generics
import [Link]; // Access elements without needing to cast
for (Integer number : numbers) {
public class GenericsExample { [Link](number);
public static void main(String[] args) {
}
// Create an ArrayList of Integer type using
Generics
// Compile-time error if you try to add
ArrayList<Integer> numbers = new a String to an ArrayList of Integers
ArrayList<>();
// [Link]("Hello"); // Error:
incompatible types
// Add some integers to the ArrayList }
[Link](10); }
[Link](20);
[Link](30);
Stack
Collection

✓ The Stack class in Java is part of the [Link] package


and is a part of the Java Collections Framework. List

✓ It represents a last-in, first-out (LIFO) stack of objects.


Vector
✓ The Stack class extends the Vector class, so it inherits
the properties of a growable array, but with added
Stack
methods that allow it to function as a stack.

Constructor Description
Stack() Constructs an empty stack.
Characteristics of Stack

✓ LIFO order: The most recently added element is the first one to be removed.
✓ Inheritance: Stack extends the Vector class, meaning it is backed by an array and
inherits methods for dynamic resizing.
✓ Thread Safety: It is synchronized, which means it is thread-safe for use in multi-
threaded applications. However, this comes with performance overhead.
✓ Legacy Class: Although the Stack class is part of the Java Collections Framework, it is
considered a legacy class. The Deque interface is recommended for stack
functionality in modern Java programs.
Methods of Stack

✓ push(E item): Adds an element to the top of the stack.


✓ pop(): Removes and returns the element at the top of the stack. It throws
EmptyStackException if the stack is empty.
✓ peek(): Returns the element at the top of the stack without removing it. It throws
EmptyStackException if the stack is empty.
✓ empty(): Returns true if the stack is empty, otherwise false.
✓ search(Object o): Returns the 1-based position of the element from the top of the
stack. Returns -1 if the element is not found.
Stack Example
import [Link]; // Peek at the top element
[Link]("Top element: " +
public class StackExample { [Link]());
public static void main(String[] args) {
// Create a stack of integers // Pop an element from the stack
Stack<Integer> stack = new Stack<>(); [Link]("Popped element: " +
[Link]());
// Push elements onto the stack
[Link](10); // Check if the stack is empty
[Link](20); [Link]("Is stack empty? " +
[Link](30); [Link]());
[Link](40);
// Search for an element in the stack
// Display the stack [Link]("Position of element 20:
for(int n: stack){ " + [Link](20));
[Link](n+" "); }
} }
LinkedList
Collection

✓ The LinkedList class in Java is part of the Java Collections


Framework. List Queue

✓ It implements the List and Deque interfaces.


AbstractList Deque
✓ It provides a doubly linked list data structure.
✓ This class allows for efficient insertion and removal of
LinkedList
elements from both ends (head and tail).

Constructor Description
LinkedList() Creates an empty LinkedList.
Creates a LinkedList containing the elements of the specified
LinkedList(Collection c)
collection.
Characteristics of LinkedList
✓ Doubly Linked List: Each element (node) has pointers to both the next and previous
elements.
✓ Dynamic Size: The size of a LinkedList can grow or shrink dynamically as elements are
added or removed.
✓ Ordered: LinkedList maintain the insertion order.
✓ Allows Duplicates: It allows duplicate elements.
✓ Null Elements: It allows null values.
✓ Slower Random Access: Since it doesn't allow direct access to elements (like an
array), accessing elements by index is slower compared to ArrayList. It needs to
traverse the list to reach a particular index.
✓ Efficient Insertions/Deletions: Inserting or deleting elements at the start or end of the list
is efficient because it doesn't require shifting elements like in an ArrayList.
Methods of LinkedList
Methods from List interface:
✓ add(E e): Adds an element at the end of the list.
✓ add(int index, E element): Inserts the specified element at the specified position in the
list.
✓ get(int index): Returns the element at the specified position.
✓ set(int index, E element): Replaces the element at the specified position with the
specified element.
✓ remove(int index): Removes the element at the specified position and return the
element.
✓ remove(Object o): Removes the specified object and return true/flase.
✓ size(): Returns the number of elements in the list
Methods of LinkedList
Methods from Deque interface (double-ended queue functionality):
✓ addFirst(E e): Adds the specified element at the front of the list.
✓ addLast(E e): Adds the specified element at the end of the list.
✓ removeFirst() / removeLast() : Removes and returns the first/last element. Throws
NoSuchElementException if queue is empty.
✓ pollFirst() / pollLast(): Removes and returns the first/last element. If the deque is empty, it
safely returns null instead of throwing an exception.
✓ peekFirst(): Retrieves the first element without removing it.
✓ peekLast(): Retrieves the last element without removing it.
Other Methods:
✓ clear(): Removes all elements from the list.
✓ contains(Object o): Returns true if the list contains the specified
LinkedList Example
import [Link]; // Access elements
[Link]("First Element: " +
public class LinkedListExample { [Link]());
public static void main(String[] args) { [Link]("Last Element: " +
// Create a LinkedList of String [Link]());
LinkedList<String> list = new LinkedList<>();
// Remove elements
// Add elements to the LinkedList [Link](); // Removes the first element
[Link]("Apple"); [Link](); // Removes the last element
[Link]("Banana");
[Link]("Cherry"); [Link]("After removing first and last
elements: " + list);
// Add elements at the beginning and the end
[Link]("Mango"); // Check if the list contains a specific element
[Link]("Grapes"); [Link]("Contains 'Banana'? " +
[Link]("Banana"));
// Iterate over the elements
[Link]("Iterating over elements:"); }
for (String fruit : list) { [Link](fruit); } }
ArrayList vs LinkedList
Feature ArrayList LinkedList

Underlying Data Structure dynamic array doubly linked list

Access Time O(1) O(n)

Insertion/Removal Time O(n) O(1)

More memory-intensive because


More memory efficient for storing
each element needs extra space to
Memory data as elements are stored
store pointers to the next and
contiguously.
previous nodes.

Use LinkedList when you require


Use ArrayList for fast access and
frequent insertions and removals,
When to Use when the list size is relatively
especially from the ends or middle
stable.
of the list.
PriorityQueue
Collection
✓ A PriorityQueue is a data structure in Java that is part of the Java
Collections Framework.
Queue
✓ It is a type of queue where each element is associated with a priority.
✓ Elements with higher priority are dequeued before elements with
AbstractQueue
lower priority.
✓ By default, the smallest element has the highest priority (for natural PriorityQueue

ordering).
Constructor Description
PriorityQueue() Creates a priority queue with natural ordering.
PriorityQueue(Comparator Creates a priority queue with the specified comparator
comparator)) that defines the ordering of the elements.
Characteristics of PriorityQueue

✓ Ordered by Priority: Elements are ordered by their natural order or by a comparator


provided at the time of creation.
✓ Non-FIFO Order: Unlike regular queues, which follow a FIFO (First-In, First-Out) order, a
priority queue follows a "priority order.“
✓ Order of Elements*: A PriorityQueue does not necessarily guarantee the order in which
elements are inserted/retrieved. It ensures that the highest priority element is at the
head of the queue. However, the internal structure may not maintain a sorted order
throughout — it only ensures that the head of the queue is always the element with the
highest priority (smallest element always has the highest priority).
✓ Efficient Operations: Insertion and deletion operations are generally logarithmic in
time complexity (O(log n)).
Methods of PriorityQueue

✓ add(E e): Inserts the specified element into the priority queue.
✓ peek(): Retrieves, but does not remove, the head of the queue (returns null if the
queue is empty).
✓ poll(): Retrieves and removes the head of the queue (returns null if the queue is
empty).
✓ remove(Object o): Removes a single instance of the specified element from the
queue, if present.
✓ size(): Returns the number of elements in the priority [Link](): Removes all
elements from the priority queue.
✓ contains(Object o): Checks if the queue contains the specified element.
PriorityQueue Example
import [Link]; // Remove and retrieve the head element
[Link]("Removed from the queue: " +
public class PriorityQueueExample { [Link]()); // Output: 10
public static void main(String[] args) {
// Create a priority queue with natural ordering // Display remaining elements
PriorityQueue<Integer> pq = new PriorityQueue<>(); [Link]("Remaining elements in the
queue: " + pq); // Output: [15, 20, 30]
// Add elements to the priority queue
[Link](10); // Check size of the queue
[Link](20); [Link]("Size of the queue: " +
[Link](15); [Link]()); // Output: 3
[Link](30); }
}
// Peek the head element (highest priority)
[Link]("Head of the queue: " + [Link]());
PriorityQueue with Custom Comparison
public class CustomCompare {
import [Link].*;
public static void main(String[] args) {
class Task{
TaskComparator taskComparator = new
String title;
TaskComparator();
int priority;
PriorityQueue<Task> tasks = new
Task(String title, int priority){
PriorityQueue<>(taskComparator);
[Link] = title;
[Link](new Task("Task 1", 10));
[Link] = priority;
[Link](new Task("Task 2", 5));
}
[Link](new Task("Task 3", 2));
void display(){
[Link](new Task("Task 4", 7));
[Link]([Link]+" "+[Link]);
[Link](new Task("Task 5", 5));
}
}
while ([Link]()>0) {
class TaskComparator implements Comparator<Task>{ Task t = [Link]();
@Override [Link]();
public int compare(Task t1, Task t2){ }
return [Link] - [Link]; } }
} }
HashMap
Map
✓ A HashMap in Java is part of the Java Collections Framework
and implements the Map interface.
AbstractMap
✓ It stores key-value pairs, where each key is unique and maps to
a specific value.
HashMap
✓ The HashMap uses a hash table for internal storage, which
allows for fast retrieval, insertion, and deletion of key-value
pairs.

Constructor Description
HashMap() Creates an empty HashMap with an initial capacity of 16
HashMap(int capacity) Creates an empty HashMap with the specified initial capacity.
Characteristics of HashMap

✓ Unordered: The elements in a HashMap are unordered. It does not guarantee any
specific order of the keys or values.
✓ Key-Value Pair: A HashMap stores data in the form of key-value pairs, where the key is
unique and the value can be duplicated.
✓ Resizing: HashMap automatically grows as elements are added.
✓ Null Keys and Values: A HashMap allows one null key and any number of null values.
✓ Non-Synchronized: HashMap is not synchronized.
✓ Efficiency: Operations like insertion, deletion, and lookup are performed in constant time,
i.e., O(1) on average, assuming a good hash function.
✓ Allows Duplicate Values: While keys must be unique, values can be duplicated across
different keys.
Methods of HashMap

✓ put(K key, V value): Adds the specified key-value pair to the map. If the key already
exists, it updates the value.
✓ get(Object key): Retrieves the value associated with the specified key, null otherwise.
✓ remove(Object key): Removes the key-value pair associated with the specified key.
✓ containsKey(Object key): Checks if the map contains the specified key.
✓ containsValue(Object value): Checks if the map contains the specified value.
✓ size(): Returns the number of key-value pairs in the map.
✓ isEmpty(): Returns true if the map is empty, otherwise false.
✓ keySet(): Returns a set of all the keys in the map.
✓ values(): Returns a collection of all the values in the map.
✓ entrySet(): Returns a set of all key-value pairs in the map as [Link] objects.
// Iterate over Map
HashMap Example Set<String> fruites = [Link]();
for(String fn : fruites){
import [Link]; [Link](fn+" : "+ [Link](fn));
import [Link]; }
// Check if a key exists
public class Ex4 { [Link]("Contains key 'Banana'? " +
public static void main(String[] args) { [Link]("Banana")); // Output: true
// Create a HashMap(fruit, price)
HashMap<String, Integer> map = new HashMap<>(); // Check if a value exists
[Link]("Contains value 40? " +
// Add key-value pairs [Link](40)); // Output: true
[Link]("Apple", 120);
[Link]("Banana", 40); // Remove a key-value pair
[Link]("Orange", 150); [Link]("Orange");

// Retrieve a value by key // Display the updated map


[Link]("Price of Apple: " + [Link]("Apple")); [Link]("Updated HashMap: " + map);
// Output: 1 // Output: {Apple=1, Banana=2}
}
}
HashSet
Collection

✓ A HashSet in Java is a collection that implements the Set


interface and is backed by a hash table (actually a HashMap Set
instance).
✓ It is used to store unique elements, meaning it does not allow AbstractSet

duplicate values.
HashSet
✓ Since it does not maintain any order, the elements in a
HashSet are unordered.

Constructor Description
HashSet() Creates a default HashSet with an initial capacity of 16.
HashSet(int initialCapacity) Creates a HashSet with the specified initial capacity.
Characteristics of HashSet

✓ Uniqueness: A HashSet does not allow duplicate elements. If an attempt to add a


duplicate element is made, it will simply not be added.
✓ Unordered: The elements in a HashSet are unordered, meaning there is no guarantee
of the order in which elements are stored or retrieved.
✓ No Indexing: It does not support indexing, so you cannot access elements by position.
✓ Null Element: A HashSet allows the storage of a single null element.
✓ Efficient Operations: The operations like add, remove, and contains have constant-
time complexity on average (O(1)), assuming a good hash function is used.
✓ Non-synchronized: A HashSet is not synchronized, meaning it is not thread-safe. If
multiple threads need to modify a HashSet concurrently, external synchronization is
required.
Methods of HashSet
✓ add(E e): Adds the specified element to the set if it is not already present. Returns true
if the element was added successfully, otherwise returns false.
✓ remove(Object o): Removes the specified element from the set if it is present. Returns
true if the element was removed, otherwise returns false.
✓ contains(Object o): Returns true if the set contains the specified element, otherwise
returns false.
✓ size(): Returns the number of elements in the set.
✓ isEmpty(): Returns true if the set is empty, otherwise returns false.
✓ clear(): Removes all elements from the set.
✓ iterator(): Returns an iterator over the elements in the set.
✓ toArray(): Returns an array containing all the elements in the set.
HashSet Example
import [Link];
// Iterate over set
public class HashSetExample { for(int n : nums){
public static void main(String[] args) { [Link](n+ " " );
// Create a HashSet to store integers }
HashSet<Integer> set = new HashSet<>();
// Remove an element
// Add elements to the HashSet [Link](20);
[Link](10); [Link]("After removing 20: " + set);
[Link](20);
[Link](30); // Check the size of the HashSet
[Link](10); // Duplicate element, won't be added [Link]("Size of HashSet: " +
[Link]()); // 2
// Display the elements of the HashSet
[Link]("HashSet elements: " + set); // Clear all elements
[Link]();
// Check if an element is present [Link]("HashSet after clear: " + set); }
[Link]("Contains 20? " + [Link](20)); // }
true
LinkedHashSet & TreeSet
LinkedHashSet
✓ The LinkedHashSet is a variation of HashSet that maintains the insertion order of
elements.
✓ Internally, it uses a hash table and a linked list, which gives it the property of retaining
the order of insertion.
✓ When you need both fast lookups and the order in which elements were added,
LinkedHashSet is a perfect choice.
TreeSet
✓ TreeSet implements the Set interface and uses a red-black tree for storage.
✓ It maintains the elements in sorted order according to their natural ordering or by a
comparator provided at the time of creation.
✓ When you need the elements to be sorted in ascending or descending order.
HashSet vs LinkedHashSet vs TreeSet
Feature HashSet LinkedHashSet TreeSet
Backed by a hash table Backed by a hash table Implemented using a Red-
Implementation
(HashMap) and a linked list Black tree
No order (unordered) Maintains insertion order Maintains natural order or
Ordering
custom order (sorted)
Does not allow duplicates Does not allow Does not allow duplicates
Duplicates
duplicates
Performance O(1) for add, remove, and O(1) for add, remove, O(log n) for add, remove,
(Average) contains and contains and contains
Unpredictable (no Iterates in the order Iterates in sorted order
Iteration Order guaranteed order) elements were inserted (ascending or custom
comparator)
Fast lookups, membership Maintaining insertion Maintaining elements in
Use Case tests, uniqueness order with fast sorted order
operations
Tracking unique items Maintaining order of Storing items in sorted order
Example Use Case (e.g., user IDs) unique items (e.g., log (e.g., leaderboard)
records)
HashSet vs ArrayList

List Set

The List is an indexed sequence. The Set is a non-indexed sequence.

The list allows duplicate elements The set doesn’t allow duplicate elements.

Elements by their position can be accessed. Position access to elements is not allowed.

Multiple null elements can be stored. Null elements can store only once.

List implementations are ArrayList, LinkedList, Set implementations are HashSet,


Vector, Stack LinkedHashSet.
Thank You

You might also like