JAVA COLLECTIONS
Java provides a Collections Framework that includes interfaces, classes, and algorithms to
store, manipulate, and retrieve data efficiently. Collections are part of the [Link] package,
and they simplify the management of groups of objects.
Hierarchy of Collection Framework
The [Link] package contains all the classes and interfaces for the Collection framework.
The Java Collections Framework is structured around key interfaces-Collection, List, Set,
Queue, and Map. Each tailored for specific data management tasks. Implementations like
ArrayList, HashSet, and HashMap offer practical solutions for working with these
collections, giving Java developers a versatile set of tools for efficient data handling.
Here are some key components:
Interfaces
1. List: Ordered collection, allows duplicates (e.g., ArrayList, LinkedList).
2. Set: No duplicates, unordered (e.g., HashSet, LinkedHashSet, TreeSet).
3. Queue: FIFO (First In, First Out), allows adding and removing elements at both ends
(e.g., PriorityQueue, Deque).
4. Map: Key-value pairs, no duplicate keys (e.g., HashMap, LinkedHashMap,
TreeMap).
Common Classes
ArrayList: Resizable array, good for random access.
HashSet: Unordered set, fast for lookups.
LinkedList: Doubly linked list, efficient for insertions and deletions.
HashMap: Fast key-value storage, unordered.
Useful Methods
Sorting: [Link](list)
Searching: [Link](list, key)
Shuffling: [Link](list)
Reversing: [Link](list)
1. List Interface
Description: A List is an ordered collection (sequence) that allows duplicate
elements.
Key Features:
o Maintains insertion order.
o Can access elements by their index (e.g., [Link](index)).
Common Implementations:
o ArrayList: Backed by a dynamic array, efficient for random access.
o LinkedList: Uses a doubly linked list, better for frequent insertions and
deletions.
Example Methods:
o add(index, element): Inserts an element at a specific position.
o remove(index): Removes an element at a specific index.
o keySet(): Returns a Set of all the keys in the map.
i) ARRAYLIST
ArrayList is one of the most commonly used classes in Java Collections Framework,
and it's part of the [Link] package. It provides a resizable-array implementation of the List
interface.
Key Features of ArrayList:
1. Dynamic Array: The size of an ArrayList can grow or shrink dynamically, unlike
arrays whose size is fixed.
2. Allows Duplicates: You can store duplicate elements in an ArrayList.
3. Maintains Order: The elements are ordered according to their insertion order.
4. Fast Random Access: Provides quick access to elements using their index.
5. Not Synchronized: It's not thread-safe by default, but you can make it synchronized
using [Link]().
6. Can Store Null: It allows null elements.
Constructors in ArrayList
1. ArrayList()
o Description: Creates an empty list with an initial capacity of 10.
o Example:
ArrayList<String> list = new ArrayList<>();
2. ArrayList(Collection<? extends E> c)
o Description: Creates a list containing the elements of the specified collection,
in the order they are returned by the collection's iterator.
o Example:
List<String> anotherList = [Link]("A", "B", "C");
ArrayList<String> list = new ArrayList<>(anotherList);
3. ArrayList(int initialCapacity)
o Description: Creates an empty list with the specified initial capacity.
o Example:
ArrayList<Integer> list = new ArrayList<>(20);
Commonly Used Methods:
Here are some frequently used methods of the ArrayList class:
Method Description
add(element) Adds an element to the list.
add(index, Inserts an element at a specified index.
element)
remove(index) Removes the element at the specified index.
get(index) Returns the element at the specified index.
set(index, element) Updates the element at the specified index with a new value.
size() Returns the number of elements in the list.
contains(element) Checks if the list contains the specified element.
indexOf(element) Returns the index of the first occurrence of the specified element (or -
1).
clear() Removes all elements from the list, making it empty.
Example
Here's a simple code snippet to show how ArrayList works:
import [Link];
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
// Inserting an element
[Link](1, "Orange");
// Accessing elements
[Link]("Element at index 2: " + [Link](2));
// Removing an element
[Link]("Banana");
// Looping through the list
for (String fruit : list) {
[Link](fruit);
}
// Checking size
[Link]("Size of the list: " + [Link]());
}
}
ii) LinkedList
The LinkedList class in Java, part of the [Link] package, implements both the List
and Deque interfaces. It represents a doubly linked list structure, making it efficient for
insertion and deletion of elements but slightly slower for random access compared to
ArrayList.
Constructors in LinkedList
1. LinkedList()
o Description: Creates an empty linked list.
o Example:
LinkedList<String> list = new LinkedList<>();
2. LinkedList(Collection<? extends E> c)
o Description: Creates a linked list containing the elements of the specified
collection, in the order they are returned by the collection's iterator.
o Example:
List<String> anotherList = [Link]("A", "B", "C");
LinkedList<String> list = new LinkedList<>(anotherList);
Methods in LinkedList
The LinkedList class provides various methods for list operations, as well as queue and stack-
like behavior (thanks to Deque implementation).
Method Description
Basic List Operations
add(E e) Adds an element to the end of the list.
add(int index, E Inserts an element at the specified index.
element)
remove(int index) Removes the element at the specified index.
get(int index) Returns the element at the specified index.
set(int index, E element) Replaces the element at the specified index with the new value.
size() Returns the number of elements in the list.
isEmpty() Checks if the list is empty.
indexOf(Object o) Returns the index of the first occurrence of the specified element,
or -1.
lastIndexOf(Object o) Returns the index of the last occurrence of the specified element,
or -1.
Other Useful Methods
clear() Removes all elements from the list.
contains(Object o) Checks if the list contains the specified element.
toArray() Converts the list into an array.
sort(Comparator<? super E> c) Sorts the list using the specified comparator.
Example Usage
Here's how you can use LinkedList with its various methods:
import [Link];
public class Example {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Orange");
[Link]("Linked List: " + list);
// Accessing elements
[Link]("First Element: " + [Link]());
[Link]("Last Element: " + [Link]());
// Removing elements
[Link]();
[Link]();
[Link]("After Removal: " + list);
// Checking size and emptiness
[Link]("Size: " + [Link]());
[Link]("Is Empty? " + [Link]());
}
}
2. Set Interface
Description: A Set is a collection that does not allow duplicate elements.
Key Features:
o Elements are unique.
o Does not guarantee any specific iteration order (unless a specific
implementation dictates it).
Common Implementations:
o HashSet: Unordered, uses a hash table for fast lookups.
o TreeSet: Sorted in natural order or by a custom comparator.
o LinkedHashSet: Maintains insertion order.
Example Methods:
o add(element): Adds an element if it’s not already present.
o contains(element): Checks if the element exists in the set.
i) HashSet
The HashSet class in Java, part of the [Link] package, implements the Set interface and
provides an efficient way to store unique elements. It uses a hash table for storing elements,
ensuring no duplicates and fast operations like add, remove, and search.
Constructors in HashSet
1. HashSet()
o Description: Creates an empty HashSet with the default initial capacity (16)
and load factor (0.75).
o Example:
HashSet<String> set = new HashSet<>();
2. HashSet(int initialCapacity)
o Description: Creates a HashSet with the specified initial capacity and default
load factor.
o Example:
HashSet<String> set = new HashSet<>(20);
3. HashSet(int initialCapacity, float loadFactor)
o Description: Creates a HashSet with the specified initial capacity and load
factor.
o Example:
HashSet<String> set = new HashSet<>(20, 0.5f);
4. HashSet(Collection<? extends E> c)
o Description: Creates a HashSet containing the elements of the specified
collection.
o Example:
List<String> list = [Link]("A", "B", "C");
HashSet<String> set = new HashSet<>(list);
Methods in HashSet
Here are the most commonly used methods of the HashSet class:
Method Description
add(E e) Adds the specified element to the set if it's not already
present.
remove(Object o) Removes the specified element from the set.
contains(Object o) Returns true if the set contains the specified element.
size() Returns the number of elements in the set.
isEmpty() Returns true if the set is empty.
clear() Removes all elements from the set.
toArray() Converts the set into an array.
addAll(Collection<? extends E> Adds all elements from the specified collection to the set.
c)
removeAll(Collection<?> c) Removes all elements in the specified collection from the
set.
retainAll(Collection<?> c) Retains only elements present in both the set and the
specified collection.
iterator() Returns an iterator to iterate over the elements of the set.
Key Points
1. No Duplicates: HashSet automatically ignores duplicate elements.
2. Unordered: The elements in the HashSet are not stored in any particular order.
3. Efficient: HashSet is optimized for fast operations like adding, removing, and
searching.
4. Null Support: A HashSet allows storing a single null value.
Example Usage
Here’s how you can use HashSet with its constructors and methods:
import [Link];
public class Example {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> set = new HashSet<>();
// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Apple"); // Duplicate, will be ignored
[Link]("HashSet: " + set);
// Checking if an element exists
[Link]("Contains Banana? " + [Link]("Banana"));
// Removing an element
[Link]("Banana");
[Link]("After Removal: " + set);
// Iterating over elements
for (String fruit : set) {
[Link](fruit);
}
// Checking size
[Link]("Size of Set: " + [Link]());
}
}
ii) TREESET:
The TreeSet class in Java, part of the [Link] package, is a collection that implements the
Set interface and is backed by a TreeMap. It guarantees that the elements will be sorted in
ascending order (by default) or as defined by a comparator.
Constructors in TreeSet
1. TreeSet()
o Description: Creates an empty TreeSet with natural ordering of elements.
o Example: TreeSet<Integer> set = new TreeSet<>();
2. TreeSet(Collection<? extends E> c)
o Description: Creates a TreeSet containing the elements of the specified
collection, sorted according to their natural order.
o Example:
List<Integer> list = [Link](5, 3, 7, 1);
TreeSet<Integer> set = new TreeSet<>(list);
3. TreeSet(SortedSet<E> s)
o Description: Creates a TreeSet containing the elements of the specified sorted
set.
o Example:
SortedSet<Integer> sortedSet = new TreeSet<>([Link](1, 2, 3));
TreeSet<Integer> set = new TreeSet<>(sortedSet);
4. TreeSet(Comparator<? super E> comparator)
o Description: Creates an empty TreeSet with the specified comparator.
o Example:
TreeSet<Integer> set = new TreeSet<>((a, b) -> b - a); // Descending order
Methods in TreeSet
Here are the commonly used methods provided by TreeSet:
Method Description
add(E e) Adds the specified element to the set if it is not already present.
remove(Object o) Removes the specified element from the set.
contains(Object o) Returns true if the set contains the specified element.
size() Returns the number of elements in the set.
isEmpty() Returns true if the set is empty.
clear() Removes all elements from the set.
iterator() Returns an iterator to traverse the elements.
first() Returns the first (lowest) element in the set.
last() Returns the last (highest) element in the set.
higher(E e) Returns the least element strictly greater than the given element, or
null.
lower(E e) Returns the greatest element strictly less than the given element, or
null.
ceiling(E e) Returns the least element greater than or equal to the given element,
or null.
floor(E e) Returns the greatest element less than or equal to the given element,
or null.
pollFirst() Retrieves and removes the first (lowest) element.
pollLast() Retrieves and removes the last (highest) element.
subSet(E from, E to) Returns a view of the portion of the set between the specified range.
headSet(E toElement) Returns a view of the portion of the set strictly less than the given
element.
tailSet(E Returns a view of the portion of the set greater than or equal to the
fromElement) element.
descendingSet() Returns a reverse order view of the elements in the set.
Key Characteristics
1. Sorted Order: Elements are automatically sorted in natural order or by a custom
comparator.
2. No Duplicates: Ensures all elements are unique.
3. Efficient Operations: Offers logarithmic time complexity for add, remove, and
search operations.
4. Null Handling: Does not allow null values.
Example Usage
Here’s how you can use TreeSet:
import [Link];
public class Example {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
// Adding elements
[Link](5);
[Link](2);
[Link](8);
[Link](1);
[Link]("TreeSet: " + set); // Automatically sorted
// Accessing specific elements
[Link]("First Element: " + [Link]());
[Link]("Last Element: " + [Link]());
// Using higher and lower methods
[Link]("Higher than 5: " + [Link](5));
[Link]("Lower than 5: " + [Link](5));
// Removing elements
[Link](); // Removes the smallest element
[Link](); // Removes the largest element
[Link]("After Removal: " + set);
}
}
3. Queue Interface
Description: A Queue represents a collection designed for holding elements prior to
processing.
Key Features:
o Operates in FIFO (First In, First Out) order.
o Has special methods to add, remove, and inspect elements.
Common Implementations:
o PriorityQueue: Elements are ordered based on their natural ordering or a
provided comparator.
o Deque (Double-ended Queue): Can add/remove elements from both ends
(e.g., ArrayDeque).
Example Methods:
o offer(element): Adds an element to the queue.
o poll(): Retrieves and removes the head of the queue.
o peek(): Retrieves, but does not remove, the head of the queue.
Deque/Queue Operations
addFirst(E e) Inserts the element at the beginning of the list
addLast(E e) Inserts the element at the end of the list.
removeFirst() Removes the first element of the list.
removeLast() Removes the last element of the list.
getFirst() Retrieves, but does not remove, the first element of the list.
getLast() Retrieves, but does not remove, the last element of the list.
pollFirst() Retrieves and removes the first element of the list, or returns null if
empty.
pollLast() Retrieves and removes the last element of the list, or returns null if
empty.
peekFirst() Retrieves, but does not remove, the first element of the list, or returns
null.
peekLast() Retrieves, but does not remove, the last element of the list, or returns
null.
4. Map Interface
Description: A Map is a collection that maps keys to values. Each key must be
unique.
Key Features:
o Keys are unique, but values can be duplicated.
o Commonly used for key-value pair lookups.
Common Implementations:
o HashMap: Unordered, allows null keys and values.
o TreeMap: Sorted based on keys.
o LinkedHashMap: Maintains insertion order.
Example Methods:
o put(key, value): Adds or updates a key-value pair.
o get(key): Retrieves the value associated with the specified key.
5. ITERATOR Interface:
The Iterator interface in Java, found in the [Link] package, is used to traverse the elements
of a collection one by one. It provides methods to iterate over a collection in a controlled
manner.
Key Features
Allows sequential access to elements in a collection (e.g., List, Set, or Map).
Ensures safe removal of elements while iterating.
Does not support random access or modification directly.
Methods in the Iterator Interface
Method Description
boolean hasNext() Returns true if there are more elements to iterate over, otherwise false.
E next() Returns the next element in the iteration.
void remove() Removes the last element returned by the iterator.
How to Use the Iterator Interface
Here's an example of how you can use an iterator to traverse a collection:
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
Iterator<String> iterator = [Link]();
// Iterating through the list
while ([Link]()) {
String fruit = [Link]();
[Link](fruit);
// Removing "Banana" while iterating
if ([Link]("Banana")) {
[Link]();
}
}
[Link]("Updated List: " + list);
}
}
References:
Java Collections
[Link]
Examples
[Link]
Set Methods
[Link]
Arraylist
[Link]
Linked List
[Link]