0% found this document useful (0 votes)
5 views

Module 1

The document provides an overview of the Java Collections Framework, detailing various interfaces and classes such as List, Set, Queue, and their implementations like ArrayList and LinkedList. It emphasizes the introduction of generics for type safety and includes examples demonstrating the use of collections, including adding, removing, and iterating over elements. Additionally, it covers methods specific to the List interface and the functionality of ArrayList and LinkedList classes.

Uploaded by

jesyjeffl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Module 1

The document provides an overview of the Java Collections Framework, detailing various interfaces and classes such as List, Set, Queue, and their implementations like ArrayList and LinkedList. It emphasizes the introduction of generics for type safety and includes examples demonstrating the use of collections, including adding, removing, and iterating over elements. Additionally, it covers methods specific to the List interface and the functionality of ArrayList and LinkedList classes.

Uploaded by

jesyjeffl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

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

4. Extending and/or adapting a collection had to be easy.

5. Allows the integration of standard arrays into the Collections Framework.

6. An iterator offers a general-purpose, standardized way of accessing the elements within a collection,
one at a time.

7. Generic methods of iterators can be used to access the objects of collection

www.cambridge.edu.in
www.cambridge.edu.in
Recent changes to collection framework
The changes were the addition of

1. Generics

• All collections are now generic

• Generics add the one feature that collections had been missing: type safety

• Prior to generics: collections stored Object references

• Resulted in run-time type mismatch errors

2. Autoboxing/unboxing

3. for-each style for loop

www.cambridge.edu.in
ArrayList
Iterable
<interface>

Collection
<interface>

List Abstract Collection


<interface> <Abstract Class>

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

Method Syntax Description


addAll boolean addAll(Collection<? extends E> c ) Adds all the elements of c to the invoking collection.
Returns true if the operation succeeded (i.e., the
elements were added). Otherwise, returns false.
clear void clear( ) Removes all elements from the invoking collection.
contains boolean contains(Object obj ) Returns true if obj is an element of the invoking
collection. Otherwise, returns false.
containsAll boolean containsAll(Collection<?> c ) Returns true if the invoking collection contains all
elements of c. Otherwise, returns false.
equals boolean equals(Object obj ) Returns true if the invoking collection and obj are
equal. Otherwise, returns false.

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.

• A list may contain duplicate elements.

• 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

Method Syntax Description


set E set(int index , E obj ) Assigns obj to the location specified by index within
the invoking list.
subList List<E> subList(int start , int end ) Returns a list that includes elements from start to
end –1 in the invoking list. Elements in the returned
list are also referenced by the invoking object.

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,

ArrayList<String> stringList = new ArrayList<>();

LinkedList<Integer> intList = new LinkedList<>();

HashMap<String, Integer> map = new HashMap<>();

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.

ArrayList<String> stringList = new ArrayList<>();

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>

List Abstract Collection


<interface> <Abstract Class>

AbstractList
<Abstract class>

ArrayList
<class>
www.cambridge.edu.in
ArrayList Class
ArrayList class extends AbstractList and implements the List interface

ArrayList is a generic class that has this declaration:

class ArrayList<E>

ArrayList has the constructors shown here:

ArrayList( ) - constructor builds an empty array list

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

• Iterating ArrayList using For-each loop

• Get and Set ArrayList

• How to Sort ArrayList

• Java ArrayList example to add elements

• Java ArrayList example to remove elements

• Java ArrayList example of retainAll() method

• Java ArrayList example of isEmpty() method

www.cambridge.edu.in
Linkedlist class
• Linkedlist is a part of the collection framework present in java.util.package

• Performing various Operations on LinkedList

Adding Elements: add(Object), add(int index, Object)

Changing Elements: set()

Removing Elements: remove(Object), remove(int index)

• Uses doubly linked list to store the objects.

• Manipulation takes less time (i.e adding and removal).

• Insertion happens fast

• Implements both list and Deque interface


Add() method of Linkedlist Class
public class Linkedlist Example{
public static void main( String[] args){
Linkedlist<String> list= new Linkedlist<>();
list.add(“Advanced”);
list.add(“Java”);
list.add(“For”);
list.add(“IV Semester”);
list.add(“BIS402”);
System.out.println(“The list is :” +list);
list.add(“ISE”);
list.add(“Department”);
System.out.println(“The new list:” +list);
}
}
Adding at the specified index
public class LinkedList Example{
public static void main(String[] args){
Linkedlist<String> link = new LinkedList();
link.add(“Apple”);
link.add(“Orange”);
link.add(“Mango”);
System.out.println(link);
link.add(2,”Grapes”);
System.out.println(link);
}
}
LinkedList addFirst() Method
used to insert a specific element at the beginning of a LinkedList.
Syntax: void addFirst(Object element)
public class LinkedListDemo {
public static void main(String args[]) {
// creating an empty LinkedList
LinkedList<String> list = new LinkedList<String>();
list.add("Grapes");
list.add("10");
list.add("20");
System.out.println("The list is:" + list);
list.addFirst("First");
list.addFirst("At");
list.addLast(“ABC”);
System.out.println("The new List is:" + list);
}
}
LinkedList addAll() Method in Java
public class LinkedListDemo { Case 1: used to append all of the elements from the collection
passed as parameter to this function to the end of a list keeping
public static void main(String args[]) { in mind the order of return by the collections iterator.
Syntax: boolean addAll(Collection C)
LinkedList<String> list = new LinkedList<String>();
Case 2: used to append all of the elements from the
list.add(“Apple"); collection passed as parameter to this function at a specific
index or position of a list.
list.add(“Oranger"); Syntax: boolean addAll(int index, Collection C)

Collection<String> collect = new ArrayList<String>();

collect.add("A");

collect.add("Computer");

System.out.println("The LinkedList is: " + list);

list.addAll(collect);

System.out.println("The new linked list is: " + list); } }


Set() method
• Used to replace any particular element in the linked list created using the linkedlist class with
another element.

• 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.

• Syntax: Linkedlist.set(int index, Object element)


Example
public class LinkedListDemo{
public static void main(String[] args){
LinkedList<String> list = new LinkedList<String>();
list.add(“Python”);
list.add(“Java”);
list.add(“c++”);
list.add(100);
list.add(200);
System.out.println(“LinkedList:” +list);
System.out.println(“Replace:” +list.set(3, “50”));
System.out.println(“Replace:” +list.set(2, “PHP”));
System.out.println(“new linkedlist:” +list);
Example
public class LinkedList Example{
public static void main(String[] args){
LinkedList<String> list = new LinkedList<String>();
list.add(“Apple”);
list.add(“Banana”);
list.add(“Cherry”);
list.set( 2, “grapes”);
System.out.println(“ List after replacement:” +list);
}
}
LinkedList remove() Method
• Types of remove() method present inside this class:
1. With no arguments inside
2. Passing index as in arguments
3. Passing object as in arguments

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.

Syntax: LinkedList.remove(int 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.

• NullPointerException : Throws an error if an null value is stored


www.cambridge.edu.in
Queue Interface

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

remove E remove( ) Removes the element at the head of the queue,


returning the element in the process. It throws
NoSuchElementException if the queue is empty.
Add add(E) This method is used to add elements at the tail of
queue. More specifically, at the last of linked-list if it
is used, or according to the priority in case of priority
queue implementation.

www.cambridge.edu.in
Element() System.out.println("Queue head now = " +

public class Demo { q.element());


public static void main(String[] args) { System.out.println("Remaining Queue
Queue<String> q = new elements...");
LinkedList<String>();
Object ob;
q.offer("abc");
q.offer("def"); while ((ob = q.poll()) != null) {
q.offer("ghi"); System.out.println(ob);
q.offer("jkl"); } }}
q.offer("mno"); Output:
q.offer("pqr"); Queue head = abc
q.offer("stu"); Removing element from queue = abc
q.offer("vwx"); Queue head now = def
Remaining Queue elements...
System.out.println("Queue head = " + def
ghi
q.element());
jkl
System.out.println("Removing element from mno
pqr
queue = " + q.remove()); stu
vwx
public class QueueExample {
Output:
public static void main(String[] args) { Queue: [apple, banana, cherry]
Queue<String> queue = new LinkedList<>(); Removed element: apple
Queue after removal: [banana, cherry]
queue.add("apple");
Peeked element: banana
queue.add("banana"); Queue after peek: [banana, cherry, date]
queue.add("cherry");
System.out.println("Queue: " + queue); // print the queue
String front = queue.remove(); // remove the element at the front of the
queue
System.out.println("Removed element: " + front);
System.out.println("Queue after removal: " + queue); // print the updated
queue
queue.add("date"); // add another element to the queue
String peeked = queue.peek(); // peek at the element at the front of the
queue
System.out.println("Peeked element: " + peeked);
System.out.println("Queue after peek: " + queue); // print the updated
queue
}}
Deque Interface

It extends Queue and declares the behaviour of a double-ended queue.


Double-ended queues can function as standard, first-in, first-out queues or as last-in, first-out stacks.
Deque is a generic interface that has this declaration: interface Deque<E>
Advantages of Deque:
• Double-Ended
• Flexibility
• Blocking Operations
Disadvantages of using Deque:
• Performance

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.

LinkedList class extends AbstractSequentialList

implements the List, Deque, Queue interfaces.

It provides a linked-list data structure.

LinkedList is a generic class that has this declaration: class LinkedList<E>

LinkedList has the two :

1. LinkedList( ) - builds an empty linked list

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.

2. Performing Various Operations on LinkedList

1. Adding Elements - add(Object), add(int index, Object)

2. Changing Elements - set()

3. Removing Elements - remove(Object), remove(int index)

4. Iterating the LinkedList – get()


PriorityQueue Class

The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner. It inherits AbstractQueue class.

PriorityQueue extends AbstractQueue and implements the Queue interface.

PriorityQueue class declaration:

public class PriorityQueue<E> extends AbstractQueue<E> implements Queue

PriorityQueues are dynamic, growing as necessary.

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

ordering.PriorityQueue<E> pq = new PriorityQueue<E>();

• PriorityQueue(int capacity)

Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.

PriorityQueue<E> pq = new PriorityQueue<E>(int initialCapacity);

• PriorityQueue(Collection<? extends E> c)

Creates a PriorityQueue containing the elements in the specified collection.

PriorityQueue<E> pq = new PriorityQueue<E>(Collection<E> c);


PriorityQueue Class
PriorityQueue defines the six constructors shown here:

• PriorityQueue(int capacity, Comparator<? super E> comp)

Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified
comparator.

PriorityQueue<E> pq = new PriorityQueue(int initialCapacity, Comparator<E> comparator);

• PriorityQueue(PriorityQueue<? extends E> c)

Creates a PriorityQueue containing the elements in the specified priority queue.

PriorityQueue<E> pq = new PriorityQueue(PriorityQueue<E> c);

• PriorityQueue(SortedSet<? extends E> c)

Creates a PriorityQueue containing the elements in the specified sorted set.

PriorityQueue<E> pq = new PriorityQueue<E>(SortedSet<E> c);


PriorityQueue Class Examples

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

• Java PriorityQueue Example: Book

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.

Few important features of ArrayDeque

1. Array deques have no capacity restrictions and they grow as necessary to support usage.

2. Null elements are prohibited in the ArrayDeque.

3. ArrayDeque class is likely to be faster than Stack when used as a stack.

4. ArrayDeque class is likely to be faster than LinkedList when used as a queue.

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.

5. SortedSet<E> tailSet(E start )

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.

6. SortedSet<E> subSet(E start , E end )

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

9. NavigableSet<E> subSet(E lowerBound , boolean lowIncl , E upperBound , boolean highIncl ) -


Returns a NavigableSet that includes all elements from the invoking set that are greater than lowerBound
and less than upperBound

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

HashSet extends AbstractSet and implements the Set interface.

It creates a collection that uses a hash table for storage.

The important points about Java HashSet class are:


• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.

HashSet is a generic class that has this declaration:

class HashSet<E>

www.cambridge.edu.in
HashSet Class
Constructor

• HashSet( ) – Default capacity 16 and fillRatio or load factor 0.75

• HashSet(Collection<? extends E> c) – Hashset with initial content of ‘c’

• HashSet(int capacity) – Hashset with initial capacity

• HashSet(int capacity, float fillRatio) – Hashset with initial capacity and fill ratio

Java HashSet Example

• ignoring duplicate elements

• to remove elements

• HashSet from another Collection

• HashSet Example: Book


www.cambridge.edu.in
LinkedHashSet
LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits
HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
• Contains unique elements only like HashSet.
• Provides all optional set operations, and permits null elements.
• Maintains insertion order.
The LinkedHashSet class extends HashSet and adds no members of its own.
It is a generic class that has this declaration:
class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold.

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:

1. LinkedHashSet(): This constructor is used to create a default HashSet

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.

• It creates a collection that uses a tree for storage.

• Objects are stored in sorted, ascending order.

• 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 has the following constructors:

• 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.

ArrayDeque<E> dq = new ArrayDeque<E>();

2. ArrayDeque(Collection<? extends E> c): This constructor is used to create an ArrayDeque


containing all the elements the same as that of the specified collection.

ArrayDeque<E> dq = new ArrayDeque<E>(Collection col);

3. ArrayDeque(int numofElements): This constructor is used to create an empty ArrayDeque and holds
the capacity to contain a specified number of elements.

ArrayDeque<E> dq = new ArrayDeque<E>(int numofElements);


www.cambridge.edu.in
• Adding Elements: In order to add an element to the ArrayDeque, we can use the methods add(),
addFirst(), addLast(), offer(), offerFirst(), offerLast() methods.

• 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

A map is an object that stores associations between keys


and values, or key/value pairs.

Keys and values are objects. Keys must be unique, but the
values may be duplicated.

one key point about maps: they don’t implement the


Iterable interface

• cannot cycle through a map using a for-each style for


loop

• can’t obtain an iterator to a map

• can obtain a collection-view of a map, which does allow


the use of either the for loop or an iterator.
Map Interface
1. The Map interface maps unique keys to values

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:

V put(Object key, Object value) It is used to insert an entry in the map.


V get(Object key) This method returns the object that contains the
value associated with the key.
Set set=map.entrySet() Converting to Set so that we can traverse

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.

• Syntax: get(Object key)

Map entrySet() method


• Used to create a set out of the same elements contained in the map.

• 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.

3. HashMap is a generic class that has this declaration:

class HashMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

The following constructors are defined:


HashMap( ) - default hash map(capacity is 16)
HashMap(Map<? extends K, ? extends V> m) - initializes the hash map by using the elements of m
HashMap(int capacity) - initializes the capacity of the hash map to capacity
HashMap(int capacity, float fillRatio) - initializes both the capacity and fill ratio
Example
• You cannot store duplicate keys in HashMap.
import java.util.*;
public class HashMapExample2{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(1,"Mango");// duplicate element
map.put(2,"Apple");
map.put(3,"Banana");
map.put(1,"Grapes"); //trying duplicate key
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
LinkedHashMap
• LinkedHashMap extends HashMap

• 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.

• LinkedHashMap is a generic class that has this declaration:

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

Here, K specifies the type of keys, and V specifies the type of values.
LinkedHashMap
LinkedHashMap defines the following constructors:

LinkedHashMap( )

LinkedHashMap(Map<? extends K, ? extends V> m)

LinkedHashMap(int capacity)

LinkedHashMap(int capacity, float fillRatio)

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.

SortedMap is generic and is declared as shown here:

interface SortedMap<K, V>

To obtain a submap, use headMap( ), tailMap( ), or subMap( ).

To get the first key in the set, call firstKey( ).

To get the last key, use lastKey( )


public static void main(String[] args) {
SortedMap<String, Integer> numbers = new TreeMap<>();
numbers.put("Two", 2);
numbers.put("One", 1);
System.out.println("SortedMap: " + numbers);
// Access the first key of the map
System.out.println("First Key: " + numbers.firstKey());
// Access the last key of the map
System.out.println("Last Key: " + numbers.lastKey());
// Remove elements from the map
int value = numbers.remove("One");
Output:
System.out.println("Removed Value: " + value); SortedMap: {One=1, Two=2}
} First Key: One
Last Key: Two
} Removed Value: 1
NavigableMap Interface

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.

NavigableMap is a generic interface that has this declaration:


interface NavigableMap<K,V>

Here, K specifies the type of the keys, and V specifies the type of the values associated with the keys.

Support methods like lowerKey, floorKey, ceilingKey and higherKey


Map.Entry Interface

The Map.Entry interface enables you to work with a map entry.

The entrySet( ) method declared by the Map interface returns a Set containing the map entries.

The only way to obtain the reference is through a iterator.

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.

The important points about Java TreeMap class are:

• Java TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.

• Java TreeMap contains only unique elements.

• Java TreeMap cannot have a null key but can have multiple null values.

• Java TreeMap is non synchronized.

• Java TreeMap maintains ascending order.


TreeMap
The following TreeMap constructors are defined:
Constructor Description
TreeMap() It is used to construct an empty tree map that will be sorted using the
natural order of its key.

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.

• It is specifically for use with keys of an enum type.

• It is a generic class that has this declaration: K must extend Enum<K>


class EnumMap<K extends Enum<K>, V>

EnumMap defines the following constructors:

EnumMap(Class<K> kType) - EnumMap of type kType


EnumMap(Map<K, ? extends V> m) - map that contains the same entries as m
EnumMap(EnumMap<K, ? extends V> em) - initialized with the values in em
Comparator interface
• Comparator is a generic interface that has this declaration:
interface Comparator<T>

• The Comparator interface defines two methods: compare( ) and equals( )

• 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> Queue<T> asLifoQueue(Deque<T> c)

Returns a last-in, first-out view of c.

• 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

value if value is not found.


Collection Algorithms
• static <T> int binarySearch(List<? extends Comparable<? super T>> list,T value)

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 <E> Collection<E> checkedCollection(Collection<E> c, Class<E> t)


Returns a run-time type-safe view of a collection. An attempt to insert an incompatible element will cause
a ClassCastException.

• static <E> List<E> checkedList(List<E> c, Class<E> t)


Returns a run-time type-safe view of a List. An attempt to insert an incompatible element will cause a
ClassCastException.

• 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.

• static int frequency(Collection<?> c, Object obj)

Counts the number of occurrences of obj in c and returns the result.

• static int indexOfSubList(List<?> list, List<?> subList)


Searches list for the first occurrence of subList. Returns the index of the first match, or –1 if no match is found.

• static int lastIndexOfSubList(List<?> list, List<?> subList)


Searches list for the last occurrence of subList. Returns the index of the last match, or –1 if no match is found.
Random Access Interface
• RandomAccess interface contains no members.

• 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

public interface Iterable<T> {

Iterator<T> iterator();

Spliterator<T> spliterator();

void forEach(Consumer <? super T> action);

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.

• next(): Returns the next element in a collection.

• 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.

2. It is similar to ArrayList, but with two differences:

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.

Vector is declared like this: class Vector<E>

Here, E specifies the type of element that will be stored.


Enumeration Interface
The Enumeration interface defines the methods by which elements in a collection of objects are

Enumerated.

It has this declaration: interface Enumeration<E> where E specifies the type of element being

enumerated.

Enumeration specifies the following two methods:

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.

Each call to nextElement( ) obtains the next object in the enumeration.


public class EnumerationExample {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Orange");
vector.add("Grapes");
Enumeration<String> enumeration =
vector.elements();
// Iterate through the elements using Enumeration
System.out.println("Elements in the Vector:"); Inside the main method:
while (enumeration.hasMoreElements()) { We create a Vector named vector capable of storing
String element = enumeration.nextElement();
strings.
We add some strings to the vector using the add method.
System.out.println(element); We obtain an Enumeration using the elements method of
} the Vector.
} We then use a while loop to iterate over the elements of
the Vector using the hasMoreElements and nextElement
} methods of the Enumeration.
Inside the loop, we print each element to the console.
Difference between Iterator and Enumeration Interface

Iterator Interface Enumeration Interface


It is a integral part of collection It is not a part of collection
framework framework. used to iterate over
elements of legacy collection classes
Supports both read and remove Supports only read operations.
operations. Provides a remove() Does not provide a built-in
method to remove elements during mechanism to remove elements
iteration. during iteration.
Thanks!

You might also like