Module 1
Module 1
1. Collection Framework
2. List Interface
3. Set Interface
4. Navigable Set Interface
5. Queue Interface
6. Deque interface
7. ArrayList
8. LinkedList
9. Hash Set
10. Linked Hashset
11. Tree Set
12. Priority Queue
13. Iterators
14. Random access interface
15. Map Interface
16. Comparator Interface
17. Vector
18. Enumeration Interface
Collection frame work
1. The Java Collections Framework standardizes handling groups of objects
2. High performance, efficient implementation(dynamic array, linked list, tree, hash tables)
3. The Java Collections Framework standardizes the way in which groups of objects are handled by
your programs
6. An iterator offers a general-purpose, standardized way of accessing the elements within a collection,
one at a time.
www.cambridge.edu.in
www.cambridge.edu.in
Recent changes to collection framework
The changes were the addition of
1. Generics
• Generics add the one feature that collections had been missing: type safety
2. Autoboxing/unboxing
www.cambridge.edu.in
ArrayList
Iterable
<interface>
Collection
<interface>
AbstractList
<Abstract class>
ArrayList
<class>
www.cambridge.edu.in
Collection Interface
• interface Collection<E>
• Collection extends the Iterable interface.
• Methods in collection interface
Method Syntax Description
add boolean add(E obj ) Adds obj to the invoking collection.
Returns true if obj was added to the collection.
Returns false if obj is already a member of the collection and
the collection does not allow duplicates.
www.cambridge.edu.in
Collection Interface
www.cambridge.edu.in
Collection Interface
Method Syntax Description
hashCode int hashCode( ) Returns the hash code for the invoking collection
isEmpty boolean isEmpty( ) Returns true if the invoking collection is empty.
Otherwise, returns false.
iterator Iterator<E> iterator( ) Returns an iterator for the invoking collection
remove boolean remove(Object obj ) Removes one instance of obj from the invoking
collection. Returns true if the element was removed.
Otherwise, returns false.
removeAll boolean removeAll(Collection<?> c ) Removes all elements of c from the invoking
collection. Returns true if the collection changed
(i.e., elements were removed). Otherwise, returns
false.
www.cambridge.edu.in
Collection Interface
Method Syntax Description
retainAll boolean retainAll(Collection<?> c ) Removes all elements from the invoking collection
except those in c. Returns true if the collection
changed (i.e., elements were removed). Otherwise,
returns false.
size int size( ) Returns the number of elements held in the invoking
collection.
toArray Object[ ] toArray( ) Returns an array in array format
stored in the invoking collection. The array elements
are copies of the collection elements.
www.cambridge.edu.in
Example
import java.util.ArrayList;
public class CollectionDemo{
Public static void main(String[] args){
ArrayList <Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
System.out.println(al);
ArrayList al2=new ArrayList();
al2.add(“aa”);
al2.add(“bb”);
al2. add(“cc”);
System.out.println(al2);
al.addAll(al2);
System.out.println(al);
}
}
import java.util.ArrayList;
import java.util.ArrayList;
public class CollectionDemo{
public class CollectionDemo{
Public static void main(String[] args){
Public static void main(String[] args){
ArrayList al = new ArrayList();
ArrayList al = new ArrayList();
al.add(“aaa”);
al.add(10);
al.add(“bbb”);
al.add(20);
al.add(“ccc”);
al.add(30);
System.out.println(al);
System.out.println(al);
al.remove(“aaa”); //Boolean Value
al.remove(10); //Will give
IndexoutofBound Exception Here it is treated as an object
Integer value is treated as index System.out.println(al);
System.out.println(al); }
} }
}
List Interface
public interface List<E> extends Collection<E>
E: type of objects
The List interface extends Collection and declares the behavior of a collection that stores a sequence of
elements.
• Elements can be inserted or accessed by their position in the list, using a zero-based index.
• In addition to the methods defined by Collection, List defines some of its own, which are summarized in
the following table.
• Several of the list methods will throw an UnsupportedOperationException if the collection cannot be
modified, and a ClassCastException is generated when one object is incompatible with another.
www.cambridge.edu.in
List Interface
Method Syntax Description
add void add(int index, Object obj) Inserts obj into the invoking list at the index passed
in index. Any pre existing elements at or beyond the
point of insertion are shifted up.
addAll boolean addAll(int index , Collection<? Inserts all elements of C into the invoking list at the
extends E> c ) index passed in index .
Any pre existing elements at or beyond the point of
insertion are shifted up. Thus, no elements are
overwritten.
Returns true if the invoking list changes and returns
false otherwise.
get E get(int index ) Returns the object stored at the specified index
within the invoking collection.
www.cambridge.edu.in
List Interface
Method Syntax Description
indexOf int indexOf(Object obj ) Returns the index of the first instance of obj in the
invoking list. If obj is not an element of the list, –1 is
returned.
lastIndexOf int lastIndexOf(Object obj ) Returns the index of the last instance of obj in the
invoking list. If obj is not an element of the list, –1 is
returned.
listIterator ListIterator<E> listIterator( ) Returns an iterator to the start of the invoking list.
listIterator(i ListIterator<E> listIterator(int index ) Returns an iterator to the invoking list that begins at
nt index ) the specified index.
remove E remove(int index ) Removes the element at position index from the
invoking list and returns the deleted element. The
resulting list is compacted. That is, the indexes of
subsequent elements are decremented by one.
www.cambridge.edu.in
List Interface
www.cambridge.edu.in
Generics
Declaration with Generics:
• When declaring a collection class, such as ArrayList, LinkedList, HashMap, etc., you can specify the type of elements it will hold
within angle brackets < >. For example,
Type Safety:
• By using generics, you ensure type safety at compile time. If you try to add an element of the wrong type to a collection, the
compiler will generate an error.
stringList.add("Hello");
stringList.add(123); // Error: The method add(String) in the type ArrayList<String> is not applicable for the arguments (int)
Example
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//implemented class is used because we cannot create object for interfaces
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
} }
www.cambridge.edu.in
Example
How to convert Array to List
We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method.
Let's see a simple example to convert array elements into List.
import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array of data type string
String[] arr={"Java","Python","PHP","C++"};
// coz we cannot add the items to the array so to add more items we convert them to list
System.out.println("Printing Array: "+Arrays.toString(arr)); //content of the objects to the string
//Converting Array to List
List<String> list=new ArrayList<String>(); //list is dynamic array <String> generic function
for(String lang:arr){
list.add(lang); }
System.out.println("Printing List: "+list);
} }
www.cambridge.edu.in
Example
How to convert List to Array
We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements
into array.
import java.util.*;
public class ListToArrayExample{
public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
fruitList.add("Mango");
fruitList.add("Banana");
fruitList.add("Apple");
fruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = fruitList.toArray(new String[fruitList.size()]);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);
}
} www.cambridge.edu.in
Example
Get and Set Element in List
The get() method returns the element at the given index, whereas the set() method changes or replaces the element.
import java.util.*;
public class ListExample2{
public static void main(String args[]){
List<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
System.out.println("Returning element: "+list.get(1));
list.set(1,"Dates");
for(String fruit:list)
System.out.println(fruit);
} }
www.cambridge.edu.in
Example
How to Sort List
There are various ways to sort the List, here we are going to use Collections.sort() method to sort the list element.
The java.util package provides a utility class Collections which has the static method sort(). Using
the Collections.sort() method, we can easily sort any List.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
Collections.sort(list1);
for(String fruit:list1)
System.out.println(fruit);
}}
www.cambridge.edu.in
Example: Contain()
import java.util.ArrayList;
public class ContainsExample {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add("Orange");
if (fruits.contains("Banana")) {
System.out.println("The list contains 'Banana'");
} else {
System.out.println("The list does not contain 'Banana'");
}
if (fruits.contains("Grapes")) {
System.out.println("The list contains 'Grapes'");
} else {
System.out.println("The list does not contain 'Grapes'");
}
}
}
ArrayList
Iterable
<interface>
Collection
<interface>
AbstractList
<Abstract class>
ArrayList
<class>
www.cambridge.edu.in
ArrayList Class
ArrayList class extends AbstractList and implements the List interface
class ArrayList<E>
ArrayList(Collection<? extends E> c) - builds an array list that is initialized with the elements of the
collection c.
ArrayList(int capacity) - builds an array list that has the specified initial capacity. The capacity is the size
of the underlying array that is used to store the elements. The capacity grows automatically as elements
are added to an array list.
www.cambridge.edu.in
ArrayList Class
void ensureCapacity (int It is used to enhance the capacity of an ArrayList instance.
requiredCapacity)
Object[] toArray() It is used to return an array containing all of the elements in this
list in the correct order.
Object clone() It is used to return a shallow copy of an ArrayList.
www.cambridge.edu.in
Examples
• Iterating ArrayList using Iterator
www.cambridge.edu.in
Linkedlist class
• Linkedlist is a part of the collection framework present in java.util.package
collect.add("A");
collect.add("Computer");
list.addAll(collect);
• This can be done by specifying the position of the element to be replaced and the new element in
the parameter of the set() method.
remove():The element is removed from the beginning or head of the linked list.
Syntax: LinkedList.remove()
remove(int index) Method :used to remove an element from a linked list from a specific position or
index.
remove(Object O): used to remove any particular element from the linked list.
Syntax: LinkedList.remove(Object O)
public static void main(String public static void main(String args[]){
args[]){
LinkedList<String> list = new
LinkedList<String> list = new LinkedList<String>();
LinkedList<String>();
list.add(“AAA");
list.add("Ghee”): list.add(“BBB);
list.add(“Sugar"); List.add(“CCC”);
list.add("10"); list.add("10");
list.add("20");
list.add("20");
System.out.println("LinkedList:" + list);
System.out.println("LinkedList:" + // Remove the head using remove()
list);
list.remove(4);
// Removing the head from List System.out.println("Final LinkedList:" +
list.remove(); list);
System.out.println("Final }}
LinkedList:" + list); Output:
}} Before Removing:[AAA, BBB,CCC 10,20]
Output: After removal:[AAA,BBB,CCC,10]
Before Removing:[Ghee, Sugar,
10,20]
After removal:[Sugar, 10,20]
LinkedList removeFirstOccurrence() Method
• used to remove the first occurrence of the specified element from the list. If there
is no occurrence of the specified element the list remains unchanged.
• Syntax: LinkedListObject.removeFirstOccurrence(Object element)
public static void main(String[] args){
Output:
LinkedList<String> list = new LinkedList<String>();
List before removing the first Occurrence of "one" : [one,
list.addLast("one"); two, three, one]
list.addLast("two"); Returned Value : true
List after removing the first Occurrence of "one" : [two,
list.addLast("three"); three, one]
list.addLast("one");
System.out.print("List before removing the "+"first Occurrence of \"one\" : ");
System.out.println(list);
// Removing first occurrence of one.
boolean returnValue = list.removeFirstOccurrence("one");
System.out.println("Returned Value : " + returnValue);
System.out.print("List after removing the"+ " first Occurrence of \"one\" : ");
System.out.println(list); }}
remove(): Used to remove an element from a linked list
public static void main(String[] args){
LinkedList<String> list = new LinkedList<String>();
list.add(“aaa”);
list.add(“bbb”);
list.add(“ccc”);
System.out.println(“LinkedList:” +list);
list.remove();
list.remove(3);
System.out.println(after removing:”, +list);
}
}
Remove(Object O) method: Used to remove any particular element from the list
Syntax: LinkedList.remove(Object O);
The parameter O is of the object type of linked list and specifies the element to be removed from the
list.
public static void main(String[] args){
LinkedList<String> list = new LinkedList<String>();
list.add(“Python”);
list.add(“Java”);
list.add(“PHP”);
list.add(“20”);
System.out.println(list);
list.remove(“PHP”);
list.remove(“Java”);
System.out.println(list);
}
}
• How do you add the elements to the list?(add())
• How do you join lists together?(addAll)
• How do you add an element at the specified index?(list.add(index, element)
• How do you get the position of a particular element in an ArrayList? (list.indexOf)
• How do you convert an ArrayList to Array? (list.toArray)
• How do you retrieve an element from a particular position of an ArrayList?(get())
• How do you replace a particular element in an ArrayList with the given element?(set())
• How do you remove the given element from an ArrayList? (list.remove()) list.clear() to remove all
the elements at once.
• How do you find the number of elements present in an ArrayList? (list.size())
Queue Interface
The Queue interface extends Collection and declares the behaviour of a queue, which is often a first-in, first-out list.
However, there are types of queues in which the ordering is based upon other criteria.
Queue is a generic interface that has this declaration: interface Queue<E> extends Collection<E>
Features of Queue interface
• FIFO concept is used for insertion and deletion of elements from a queue.
• The Java Queue provides support for all of the methods of the Collection interface including deletion, insertion,
etc.
• Queues that are present in the util package are known as Unbounded Queues.
• Queues that are present in the util.concurrent package are known as bounded Queues.
• All Queues barring the Deques facilitates removal and insertion at the head and tail of the queue; respectively. In
fact, deques support element insertion and removal at both ends.
www.cambridge.edu.in
Queue Interface methods
Method Syntax Description
element E element( ) Returns the element at the head of the queue. The
element is not removed. It throws
NoSuchElementException ( meaning the element
which we are searching does not exist) if the queue
is empty.
offer boolean offer(E obj ) Attempts to add obj to the queue. Returns true if obj
was added and false otherwise.
peek E peek( ) Returns the element at the head of the queue. It
returns null if the queue is empty. The element is not
removed.
poll E poll( ) Returns the element at the head of the queue,
removing the element in the process. It returns null if
the queue is empty. www.cambridge.edu.in
Queue Interface methods
Method Syntax Description
www.cambridge.edu.in
Element() System.out.println("Queue head now = " +
www.cambridge.edu.in
Deque Interface methods
Method Syntax Description
addFirst void addFirst(E obj ) Adds obj to the head of the deque. Throws an
IllegalStateException if a capacity-restricted deque is
out of space.
addLast void addLast(E obj ) Adds obj to the tail of the deque. Throws an
IllegalStateException if a capacity-restricted deque is
out of space.
descendingIt Iterator<E> descendingIterator( ) Returns an iterator that moves from the tail to the
erator head of the deque. In other words, it returns a reverse
iterator.
getFirst E getFirst( ) Returns the first element in the deque. The object is
not removed from the deque. It throws
NoSuchElementException if the deque is empty.
www.cambridge.edu.in
Deque Interface methods
Method Syntax Description
getLast E getLast( ) Returns the last element in the deque. The object is
not removed from the deque. It throws
NoSuchElementException if the deque is empty.
offerFirst boolean offerFirst(E obj ) Attempts to add obj to the head of the deque. Returns
true if obj was added and false otherwise. Therefore,
this method returns false when an attempt is made to
add obj to a full, capacity-restricted deque.
offerLast boolean offerLast(E obj ) Attempts to add obj to the tail of the deque. Returns
true if obj was added and false otherwise.
peekFirst E peekFirst( ) Returns the element at the head of the deque. It
returns null if the deque is empty. The object is not
removed.
www.cambridge.edu.in
Deque Interface methods
Method Syntax Description
peekLast E peekLast( ) Returns the element at the tail of the deque. It
returns null if the deque is empty. The object is not
removed.
pollFirst E pollFirst( ) Returns the element at the head of the deque,
removing the element in the process. It returns null
if the deque is empty.
pollLast E pollLast( ) Returns the element at the tail of the deque,
removing the element in the process. It returns null
if the deque is empty.
pop( ) E pop( ) Returns the element at the head of the deque,
removing it in the process. It throws
NoSuchElementException if the deque is empty.
www.cambridge.edu.in
Deque Interface methods
Method Syntax Description
push void push(E obj ) Adds obj to the head of the deque. Throws an
IllegalStateException if a capacity-restricted deque is
out of space.
removeFirst( ) E removeFirst( ) Returns the element at the head of the deque,
removing the element in the process. It throws
NoSuchElementException if the deque is empty.
removeFirstOc boolean removeFirstOccurrence(Object obj ) Removes the first occurrence of obj from the deque.
currence Returns true if successful and false if the deque did
not contain obj .
removeLast E removeLast( ) Returns the element at the tail of the deque, removing
the element in the process. It throws
NoSuchElementException if the deque is empty.
removeLastOcc boolean removeLastOccurrence(Object obj ) Removes the last occurrence of obj from the deque.
urrence Returns true if successful and false if the deque did
not contain
www.cambridge.edu.in
public class DequeExample {
public static void main(String[] args){
Deque<String> deque= new LinkedList<String>(); Output:
[Element 6 (Head), Element 4 (Head), Element 2 (Head),
deque.add("Element 1 (Tail)"); // Add at the last Element 1 (Tail), Element 3 (Tail), Element 5 (Tail)]
deque.addFirst("Element 2 (Head)"); // Add at the first
deque.addLast("Element 3 (Tail)"); // Add at the last Deque after removing first and last: [Element 4 (Head),
Element 2 (Head), Element 1 (Tail), Element 3 (Tail)]
deque.push("Element 4 (Head)"); // Add at the first
deque.offer("Element 5 (Tail)"); // Add at the last
deque.offerFirst("Element 6 (Head)"); // Add at the first
System.out.println(deque + "\n");
deque.removeFirst();
deque.removeLast();
System.out.println("Deque after removing “ + "first and last:
“ + deque);
// We can remove the first element or the last element.
}}
public class DequeExample {
public static void main(String[] args) { After offerFirst Traversal...
jai
Deque<String> deque=new ArrayDeque<String>();
arvind
deque.offer("arvind"); vimal
deque.offer("vimal"); Mukul
deque.add("mukul"); After pollLast() Traversal...
deque.offerFirst("jai"); vimal
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s); }
deque.poll();
deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Adding elements to Deque
• add() - inserts the specified element at the end of the array deque
• addFirst() - inserts the specified element at the beginning of the array deque
• addLast() - inserts the specified at the end of the array deque (equivalent to If the array deque is full, all these
add())
methods add(), addFirst() and
import java.util.ArrayDeque;
class Main { addLast() throws
public static void main(String[] args) { IllegalStateException.
ArrayDeque<String> animals= new ArrayDeque<>();
// Using add()
animals.add("Dog");
// Using addFirst()
animals.addFirst("Cat");
// Using addLast()
animals.addLast("Horse");
System.out.println("ArrayDeque: " + animals);
}}
Inserting elements in deque
• offer() - inserts the specified element at the end of the array deque
• offerFirst() - inserts the specified element at the beginning of the array
deque
• offerLast() - inserts the specified element at the end of the array deque
offer(), offerFirst() and offerLast()
import java.util.ArrayDeque;
returns true if the element is
class Main { successfully inserted; if the array
public static void main(String[] args) { deque is full, these methods return
false.
Deque<String> animals= new ArrayDeque<>();
// Using offer()
animals.offer("Dog");
// Using offerFirst()
animals.offerFirst("Cat");
// Using offerLast()
animals.offerLast("Horse");
System.out.println("ArrayDeque: " + animals);
}}
LinkedList Class
• This class is an implementation of the LinkedList data structure which is a linear data structure where the
elements are not stored in contiguous locations and every element is a separate object with a data part and
address part.
• The elements are linked using pointers and addresses. Each element is known as a node.
2. LinkedList(Collection<? extends E> c) - builds a linked list that is initialized with the elements of the
collection c.
LinkedList Class
1. The following implementation demonstrates how to create and use a linked list.
The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner. It inherits AbstractQueue class.
The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according
to the natural ordering, or by a Comparator provided at queue construction time, depending on which
constructor is used.
www.cambridge.edu.in
PriorityQueue Class
PriorityQueue defines the six constructors shown here:
• PriorityQueue( )
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural
• PriorityQueue(int capacity)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified
comparator.
Example:
The example below explains the following basic operations of the priority queue.
• boolean add(E element): This method inserts the specified element into this priority queue.
• public peek(): This method retrieves, but does not remove, the head of this queue, or returns null if this
queue is empty.
• public poll(): This method retrieves and removes the head of this queue, or returns null if this queue is
empty.
PriorityQueue Class Examples
Example:
1. Adding Elements: In order to add an element in a priority queue, we can use the add() method. The
insertion order is not retained in the PriorityQueue. The elements are stored based on the priority
order which is ascending by default.
2. Removing Elements: In order to remove an element from a priority queue, we can use
the remove() method. If there are multiple such objects, then the first occurrence of the object is
removed. Apart from that, the poll() method is also used to remove the head and return it.
3. Accessing the elements: Since Queue follows the First In First Out principle, we can access only the
head of the queue. To access elements from a priority queue, we can use the peek() method.
4. Iterating the PriorityQueue: There are multiple ways to iterate through the PriorityQueue. The
most famous way is converting the queue to the array and traversing using the for loop. However, the
queue also has an inbuilt iterator which can be used to iterate through the queue.
PriorityQueue Class
• Java PriorityQueue Example
Let's see a PriorityQueue example where we are adding books to queue and printing all the books. The
elements in PriorityQueue must be of Comparable type. String and Wrapper classes are Comparable by
default. To add user-defined objects in PriorityQueue, you need to implement Comparable interface.
ArrayDeque class
1. The ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation
of the Deque interface.
2. It is also known as Array Double Ended Queue or Array Deck. This is a special kind of array that
grows and allows users to add or remove an element from both sides of the queue.
1. Array deques have no capacity restrictions and they grow as necessary to support usage.
www.cambridge.edu.in
Set Interface Methods
This method is used to add a specific element to the set. The function adds the
add(element) element only if the specified element is not already present in the set else the function
returns False if the element is already present in the Set.
This method is used to append all of the elements from the mentioned collection to
addAll(collection) the existing set. The elements are added randomly without following any specific
order.
This method is used to remove all the elements from the set but not delete the set.
clear()
The reference for the set still exists.
contains(element) This method is used to check whether a specific element is present in the Set or not.
This method is used to check whether the set contains all the elements present in the
containsAll(collection) given collection or not. This method returns true if the set contains all the elements
and returns false if any of the elements are missing.
www.cambridge.edu.in
Set Interface
1. The Set interface defines a set.
2. It extends Collection and declares the behaviour of a collection that does not allow duplicate
elements.
3. Therefore, the add() method returns false if an attempt.
4. Set is a generic interface that has this declaration:
public interface Set extends Collection;
www.cambridge.edu.in
Set Interface Methods
isEmpty() This method is used to check whether the set is empty or not.
This method is used to return the iterator of the set. The elements from the set
iterator()
are returned in a random order.
This method is used to remove the given element from the set. This method
remove(element) returns True if the specified element is present in the Set otherwise it returns
False.
This method is used to remove all the elements from the collection which are
removeAll(collection) present in the set. This method returns true if this set changed as a result of the
call.
This method is used to retain all the elements from the set which are mentioned
retainAll(collection) in the given collection. This method returns true if this set changed as a result
of the call.
This method is used to get the size of the set. This returns an integer value
size()
which signifies the number of elements.
toArray() This method is used to form an array of the same elements as that of the Set.
Hashcode() returns a hash code value (address of the element in the set)
www.cambridge.edu.in
isEmpty() Method
SortedSet Interface
1. The SortedSet interface extends Set and declares the behaviour of a set sorted in ascending order.
2. SortedSet is a generic interface that has this declaration:
interface SortedSet<E>
Here, E specifies the type of objects that the set will hold.
In addition to those methods defined by Set, the SortedSet interface declares the methods.
1. Comparator<? super E> comparator( )
Returns the invoking sorted set’s comparator, If the natural ordering is used for this set, null is
returned.
2. E first( )
Returns the first element in the invoking sorted set.
3. E last( )
Returns the first element in the invoking sorted set.
www.cambridge.edu.in
SortedSet
4. SortedSet<E> headSet(E end )
Returns a SortedSet containing those elements less than end that are contained in the invoking sorted
set. Elements in the returned sorted set are also referenced by the invoking sorted set.
Returns a SortedSet that contains those elements greater than or equal to start that are contained in
the sorted set. Elements in the returned set are also referenced by the invoking object.
Returns a SortedSet that includes those elements between start and end– 1. Elements in the returned
collection are also referenced by the invoking object.
www.cambridge.edu.in
SortedSet Interface
Exception:
1. NoSuchElementException - when no items are contained in the invoking set.
2. ClassCastException - object is incompatible with the elements in a set.
3. NullPointerException- if an attempt is made to use a null object and null is not allowed in the set.
4. IllegalArgumentException - invalid argument is used
www.cambridge.edu.in
Headset() Method
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Original TreeSet: [10, 20, 30, 40, 50]
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(10); HeadSet up to 30: [10, 20]
treeSet.add(20);
treeSet.add(30);
treeSet.add(40);
treeSet.add(50);
System.out.println("Original TreeSet: " + treeSet);
TreeSet<Integer> headSet = (TreeSet<Integer>)
treeSet.headSet(30);
System.out.println("HeadSet up to 30: " +
headSet);
}
}
Tailset() method
public class Main {
public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();
Original TreeSet: [10, 20, 30, 40, 50]
treeSet.add(10);
HeadSet up to 30: [30, 40,50]
treeSet.add(20);
treeSet.add(30);
treeSet.add(40);
treeSet.add(50);
System.out.println("Original TreeSet: " + treeSet);
TreeSet<Integer> tailSet = (TreeSet<Integer>)
treeSet.tailSet(30);
System.out.println("TailSet starting from 30: " +
tailSet);
}
}
Subset() method
public class Main {
public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(10); Original TreeSet: [10, 20, 30, 40, 50]
treeSet.add(20); Subset between 20 (inclusive) and 40 (exclusive):
treeSet.add(30);
[20, 30]
treeSet.add(40);
treeSet.add(50);
System.out.println("Original TreeSet: " + treeSet);
TreeSet<Integer> subset = (TreeSet<Integer>)
treeSet.subSet(20, 40);
System.out.println("Subset between 20 (inclusive) and
40 (exclusive): " + subset);
}
}
NavigableSet
The NavigableSet interface extends SortedSet and declares the behavior of a collection that supports the
retrieval of elements based on the closest match to a given value or values.
NavigableSet is a generic interface that has this declaration: interface NavigableSet<E>
Here, E specifies the type of objects that the set will hold.
Methods in the interface are:
1. E ceiling(E obj ) - Searches the set for the smallest element
2. Iterator<E> descendingIterator( ) - iterator that moves from the greatest to least
3. NavigableSet<E> descendingSet( ) - reverse of the invoking set
4. E floor(E obj ) - Searches the set for the largest element e such that e <= obj / NULL
5. E higher(E obj ) - Searches the set for the largest element e such that e > obj / NULL
6. E lower(E obj ) - largest element e such that e < obj /NULL
www.cambridge.edu.in
NavigableSet
7. E pollFirst( ) - Returns the first element, removing the element in the process / NULL
8. E pollLast( ) - Returns the last element, removing the element in the process./NULL
10. NavigableSet<E> headSet(E upperBound , boolean incl ) – Returns a set with elements less than
upper bound, incl-is true, include upper bound element also
11. NavigableSet<E> tailSet(E lowerBound , boolean incl ) - Returns a set with elements greater than
lower bound, incl-is true, include upper bound element also
www.cambridge.edu.in
Navigable headset()
public class HeadSetExample {
public static void main(String[] args) {
NavigableSet<Integer> set = new TreeSet<>();
set.add(1);
set.add(3); Elements in the headSet: [1, 3, 5, 7]
set.add(5);
set.add(7);
set.add(9);
NavigableSet<Integer> headSet = set.headSet(7,
true);
System.out.println("Elements in the headSet: " +
headSet);
}
}
Navigable tailset()
public class TailSetExample {
public static void main(String[] args) {
NavigableSet<Integer> set = new TreeSet<>();
set.add(1);
set.add(3); Elements in the headset:[5, 7, 9]
set.add(5);
set.add(7);
set.add(9);
NavigableSet<Integer> tailSet = set.tailSet(5, true); // true
indicates inclusive of the specified element
System.out.println("Elements in the tailSet: " + tailSet);
}
}
Navigable Subset()
import java.util.NavigableSet;
import java.util.TreeSet;
public class SubSetExample {
public static void main(String[] args) {
NavigableSet<Integer> set = new TreeSet<>(); Elements in the subSet: [3, 5]
set.add(1);
set.add(3);
set.add(5);
set.add(7);
set.add(9);
NavigableSet<Integer> subSet = set.subSet(3, true,
7, false);
System.out.println("Elements in the subSet: " +
subSet);
}
}
public class CeilingExample {
public static void main(String[] args) {
NavigableSet<Integer> set = new TreeSet<>();
set.add(1); Output:
set.add(2); No ceiling found for 6 in the set.
set.add(3);
set.add(4);
set.add(5);
//set.add(6);
int value = 6;
int ceilingElement = set.ceiling(value);
if (ceilingElement != Integer.MIN_VALUE) {
System.out.println("Ceiling for " + value + " is: " +
ceilingElement);
} else {
System.out.println("No ceiling found for " + value + " in the set.");
}
}
}
public class FloorExample {
public static void main(String[] args) {
NavigableSet<Integer> set = new TreeSet<>();
set.add(1); Output:
set.add(3); Floor for 6 is : 5
set.add(5);
set.add(7);
set.add(9);
int value = 6;
Integer floorElement = set.floor(value);
if (floorElement != null) {
System.out.println("Floor for " + value + " is: " + floorElement);
} else {
System.out.println("No floor found for " + value + " in the set.");
}
}
}
HashSet Class
class HashSet<E>
www.cambridge.edu.in
HashSet Class
Constructor
• HashSet(int capacity, float fillRatio) – Hashset with initial capacity and fill ratio
• to remove elements
www.cambridge.edu.in
• LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were
inserted.
• This allows insertion-order iteration over the set.
• That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in
the order in which they were inserted.
• This is also the order in which they are contained in the string returned by
• toString( ) when called on a LinkedHashSet object.
www.cambridge.edu.in
LinkedHashSet
Constructors of LinkedHashSet class:
2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection
C.
3. LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the integer
mentioned in the parameter.
4. LinkedHashSet(int capacity, float fillRatio): Can be used to initialize both the capacity and the fill
ratio, also called the load capacity of the LinkedHashSet with the arguments mentioned in the
parameter.
www.cambridge.edu.in
TreeSet Class
TreeSet extends AbstractSet and implements the NavigableSet interface.
• Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large
amounts of sorted information that must be found quickly.
www.cambridge.edu.in
TreeSet Class
TreeSet is a generic class that has this declaration:
class TreeSet<E>
Here, E specifies the type of objects that the set will hold.
• TreeSet( ) - used to build an empty TreeSet object in which elements will get stored in default natural sorting
order.
• TreeSet(Collection<? extends E> c) - build a TreeSet object containing all the elements from the given
collection in which elements will get stored in default natural sorting order.
• TreeSet(Comparator<? super E> comp) – builds empty treeset with external sorting comparator
• TreeSet(SortedSet<E> ss) - build a TreeSet object containing all the elements from the given sortedset in which
elements will get stored in default natural sorting order.
www.cambridge.edu.in
TreeSet Class
Examples:
1. how to create and use a TreeSet
2. Accessing the Elements - methods like contains(), first(), last()
3. Removing the Values - using the remove() method
4. Iterating through the TreeSet:
www.cambridge.edu.in
public class Main {
// Constructor 3: TreeSet from a collection
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 5);
// Constructor 1: Default constructor
TreeSet<Integer> treeSet1 = new TreeSet<>(); TreeSet<Integer> treeSet3 = new TreeSet<>(list);
treeSet1.add(5); System.out.println("TreeSet 3: " + treeSet3);
treeSet1.add(3); // Constructor 4: TreeSet from a sorted set
treeSet1.add(8);
SortedSet<Integer> sortedSet = new
System.out.println("TreeSet 1: " + treeSet1);
TreeSet<>(Arrays.asList(30, 15, 25));
// Constructor 2: TreeSet with custom
comparator TreeSet<Integer> treeSet4 = new
TreeSet<String> treeSet2 = new TreeSet<>(sortedSet);
TreeSet<>(Comparator.reverseOrder());
treeSet2.add("Apple"); System.out.println("TreeSet 4: " + treeSet4);
treeSet2.add("Banana"); }
treeSet2.add("Orange"); }
System.out.println("TreeSet 2: " + treeSet2);
TreeSet 1: [3, 5, 8]
TreeSet 2: [Orange, Banana, Apple]
TreeSet 3: [5, 10, 20]
TreeSet 4: [15, 25, 30]
ArrayDeque class
Declaration:
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable
www.cambridge.edu.in
ArrayDeque class
Constructors of ArrayDeque class
1. ArrayDeque(): This constructor is used to create an empty ArrayDeque and by default holds an initial
capacity to hold 16 elements.
3. ArrayDeque(int numofElements): This constructor is used to create an empty ArrayDeque and holds
the capacity to contain a specified number of elements.
• Accessing the Elements: After adding the elements, if we wish to access the elements, we can use
inbuilt methods like getFirst(), getLast(), etc.
• Removing Elements: In order to remove an element from a deque, there are various methods
available. Since we can also remove from both the ends, the deque interface provides us
with removeFirst(), removeLast() methods. Apart from that, this interface also provides us with
the poll(), pop(), pollFirst(), pollLast() methods where pop() is used to remove and return the head of
the deque. However, poll() is used because this offers the same functionality as pop() and doesn’t
return an exception when the deque is empty.
• Iterating through the Deque: Since a deque can be iterated from both the directions, the iterator
method of the deque interface provides us two ways to iterate. One from the first and the other from
the back: iterator(), descendingIterator()
Maps
Keys and values are objects. Keys must be unique, but the
values may be duplicated.
2. Given a key and a value, you can store the value in a Map object. After
the value is stored, you can retrieve it by using its key.
Map is generic:
interface Map<K, V> K specifies the type of keys, and V specifies the type of values
Methods supported are:
To do this, you can use the entrySet( ) method. It returns a Set that contains the elements in the map
Map Interface
Methods supported are:
Set keySet() It returns the Set view containing all the keys.
Collection values() It returns a collection view of the values contained in the map.
V replace(K key, V value) It replaces the specified value for a specified key.
Put() Method
• Syntax: V put(K key, V value)
public class MapPutExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
System.out.println("Map after adding elements: " + map);
// Replace the value associated with key 'Two' and store the previous value
Integer oldValue = map.put("Two", 22);
// Display the previous value associated with key 'Two'
System.out.println("Previous value for key 'Two': " + oldValue);
// Display the map after updating the value for key 'Two' Output:
System.out.println("Map after updating 'Two': " + map); Map after adding elements: {One=1, Two=2}
Previous value for key 'Two': 2
} Map after updating 'Two': {One=1, Two=22}
}
putAll() Method
public class GfG {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(3, "Three");
map.put(5, "Five");
map.put(7, "Seven");
map.put(9, "Nine");
System.out.println(map);
Map<Integer, String> mp = new HashMap<>();
mp.put(10, "Ten");
mp.put(30, "Thirty");
mp.put(50, "Fifty");
Output:
map.putAll(mp); {1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
System.out.println(map); {1=One, 50=Fifty, 3=Three, 5=Five, 7=Seven, 9=Nine,
10=Ten, 30=Thirty}
}}
Get() Method
• The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a
particular key mentioned in the parameter.
• It returns NULL when the map contains no such mapping for the key.
• It basically returns a set view of the map or we can create a new set and store the map elements
into them.
public class Map_Demo {
public static void main(String[] args){
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(“Apple", 10);
map.put("4", 15);
map.put(“Grapes", 20);
map.put(“Cherry", 25);
map.put("You"", 30);
System.out.println("Initial Mappings are: " + map);
System.out.println("The Value is: " + map.get("Grapes"));
System.out.println("The Value is: " + map.get("You"));
}
}
HashMap Class
1. The HashMap class extends AbstractMap and implements the Map interface. It uses a hash table
to store the map.
2. This allows the execution time of get( ) and put( ) to remain constant even for large sets.
Here, K specifies the type of keys, and V specifies the type of values.
• It maintains a linked list of the entries in the map, in the one order in which they were inserted.
• This allows insertion-order iteration over the map. That is, when iterating through a collection-view
of a LinkedHashMap, the elements will be returned in the order in which they were inserted.
Here, K specifies the type of keys, and V specifies the type of values.
LinkedHashMap
LinkedHashMap defines the following constructors:
LinkedHashMap( )
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio, boolean Order) - The last form allows you to specify
whether the elements will be stored in the linked list by insertion order, or by order of last access.
SortedMap Interface
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending order
based on the keys.
It extends SortedMap and declares the behavior of a map that supports the retrieval of entries based on
the closest match to a given key or keys.
Here, K specifies the type of the keys, and V specifies the type of the values associated with the keys.
The entrySet( ) method declared by the Map interface returns a Set containing the map entries.
Each of these set elements is a Map.Entry object. Map.Entry is generic and is declared like this:
interface Map.Entry<K, V>
public class MapEntryExample {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> map = new HashMap<>();
// Add some key-value pairs
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// Iterate through the entries using Map.Entry
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
TreeMap
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing
key-value pairs in sorted order.
The TreeMap class extends AbstractMap and implements the NavigableMap interface.
• Java TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
• Java TreeMap cannot have a null key but can have multiple null values.
TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will be sorted using
comparator) the comparator comp.
TreeMap(Map<? extends K,? extends V> It is used to initialize a treemap with the entries from m, which will be
m) sorted using the natural order of the keys.
TreeMap(SortedMap<K,? extends V> sm) It is used to initialize a treemap with the entries from the SortedMap sm,
which will be sorted in the same order as sm.
class Main {
for(Map.Entry<String, Double> me : set) {
public static void main(String args[]) {
System.out.print(me.getKey() + ": ");
// Create a tree map.
System.out.println(me.getValue());
TreeMap<String, Double> tm = new TreeMap<String,
}
Double>();
System.out.println();
// Put elements to the map.
// Deposit 1000 into John Doe's account.
tm.put("John Doe", new Double(3434.34));
double balance = tm.get("John Doe");
tm.put("Tom Smith", new Double(123.22));
tm.put("John Doe", balance + 1000);
tm.put("Jane Baker", new Double(1378.00));
System.out.println("John Doe's new balance: "
tm.put("Tod Hall", new Double(99.22));
+tm.get("John Doe"));
tm.put("Ralph Smith", new Double(-19.08));
}
// Get a set of the entries.
}
Set<Map.Entry<String, Double>> set = tm.entrySet();
// Display the elements.
IdentityHashMap
IdentityHashMap extends AbstractMap and implements the Map interface
It is similar to HashMap except that it uses reference equality when comparing
elements.
IdentityHashMap is a generic class that has this declaration:
class IdentityHashMap<K, V>
The API documentation explicitly states that IdentityHashMap is not for general use
EnumMap Class
• EnumMap extends AbstractMap and implements Map.
• The compare( ) - method, shown here, compares two elements for order:
int compare(T obj1, T obj2) and returns 0, +ve, -ve
• By overriding compare( ), you can alter the way that objects are ordered
• The equals( ) method tests whether an object equals the invoking comparator: boolean equals(Object
obj) – return true/false
Collection Algorithms
Collections Framework defines several algorithms that can be applied to collections and maps.
• static <T> Boolean addAll(Collection <? super T> c, T ... elements)
Inserts the elements specified by elements into the collection specified by c. Returns true if the
elements were added and false otherwise.
• static <T>int binarySearch(List<? extends T> list, T value, Comparator<? super T> c)
Searches for value in list ordered according to c. Returns the position of value in list, or a negative
Searches for value in list. The list must be sorted. Returns the position of value in list, or a negative value
if value is not found.
• static <K, V> Map<K, V> checkedMap(Map<K, V> c, Class<K> keyT, Class<V> valueT)
Returns a run-time type-safe view of a Map. An attempt to insert an incompatible element will cause a
ClassCastException.
Collection Algorithms
• static <E> List<E> checkedSet(Set<E> c, Class<E> t)
Returns a run-time type-safe view of a Set. An attempt to insert an incompatible element will cause a
ClassCastException.
• However, by implementing this interface, a collection signals that it supports efficient random access
to its elements.
• By checking for the RandomAccess interface, client code can determine at run time whether a
collection is suitable for certain types of random access operations—especially as they apply to large
collections.
• RandomAccess is implemented by ArrayList and by the legacy Vector class, among others.
Iterator Interface
It belongs to java.lang package. In general, an object Implementing Iterable allows it to be iterated. An
iterable interface allows an object to be the target of enhanced for loop(for-each loop)
Definition of Iterable
Iterator<T> iterator();
Spliterator<T> spliterator();
www.cambridge.edu.in
Methods of Iterator
Using Iterator<T> interface
• hasNext(): It returns false if we have reached the end of the collection, otherwise returns true. This
method is used to determine whether the next() method is to be called or not.
• remove(): Removes the last element returned by the iterator from the collection.
• forEachRemaining(): Performs the given action for each remaining element in a collection, in
sequential order.
www.cambridge.edu.in
public class IteratorRemoveExample {
public static void main(String[] args) { System.out.println("Modified list after removing
ArrayList<Integer> numbers = new ArrayList<>(); even numbers:");
numbers.add(1);
for (int num : numbers) {
numbers.add(2);
System.out.println(num);
numbers.add(3);
numbers.add(4); }
numbers.add(5); }
Iterator<Integer> iterator = numbers.iterator(); }
// Get an Iterator for the ArrayList
System.out.println("Numbers in the list:"); • Obtains an Iterator for the numbers ArrayList using the
while (iterator.hasNext()) { iterator method.
int num = iterator.next();
• The iterator is used to iterate over the elements of the
System.out.println(num);
numbers ArrayList.
if (num % 2 == 0) {
// Remove even numbers using Iterator.remove() • Each element (num) is printed to the console.
iterator.remove(); • If the current number is even, it is removed from the list
} using iterator.remove().
}
The Legacy Classes and Interfaces
• When collections were added (by J2SE 1.2), several of the original classes were reengineered to
support the collection interfaces.
• While no classes have actually been deprecated, one has been rendered obsolete.
• The legacy classes are supported because there is still code that uses them.
• None of the collection classes are synchronized, but all the legacy classes are synchronized.
www.cambridge.edu.in
The Legacy Classes and Interfaces
The legacy classes defined by java.util are shown here:
• Dictionary
• Hashtable
• Properties
• Stack
• Vector
There is one legacy interface called Enumeration.
Vector
1. Vector implements a dynamic array.
1. Vector is synchronized.
Being synchronized means that the methods of the Vector class are designed to be safely accessed by
multiple threads concurrently.
2. It contains many legacy methods that are not part of the Collections.
Enumerated.
It has this declaration: interface Enumeration<E> where E specifies the type of element being
enumerated.
boolean hasMoreElements( )
E nextElement( )
When implemented, hasMoreElements( ) must return true while there are still more elements to
extract, and false when all the elements have been enumerated.