[go: up one dir, main page]

0% found this document useful (0 votes)
14 views165 pages

Unit 1 Class Notes

dfvbsfbxbs

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views165 pages

Unit 1 Class Notes

dfvbsfbxbs

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

UNIT 1 – COLLECTIONS FRAMEWORK AND UTILITY CLASSES

▪1
UNIT – I
COLLECTIONS FRAMEWORK AND UTILITY CLASSES

Introduction to Collections Framework


Collection Interface
Methods in Collection Interface
Iterable and Iterator Interfaces
List Interface - ArrayList - LinkedList
Set Interface – HashSet - Linked Hash Set - Tree Set
Map Interface - HashMap – LinkedHashMap – TreeMap
Queue Interface – PriorityQueue
Deque Interface
Utility Classes

Reinforcement Learning 2
Introduction to Collections Framework

Reinforcement Learning 3
Introduction to Collections Framework

A collection is an object that represents a group of


objects.
A collections framework is a unified architecture for
representing and manipulating collections,
enabling collections to be manipulated independently of
implementation details.

Reinforcement Learning 4
Introduction to Collections Framework

The primary advantages of a collections framework are that


it:
✓ Reduces programming effort by providing data structures and
algorithms so you don't have to write them yourself.
✓ Increases performance by providing high-performance implementations
of data structures and algorithms. Because the various implementations of
each interface are interchangeable, programs can be tuned by switching
implementations.
✓ Provides interoperability between unrelated APIs by establishing a
common language to pass collections back and forth.
✓ Reduces the effort required to learn APIs by requiring you to learn
multiple adhoc collection APIs.
✓ Reduces the effort required to design and implement APIs by not
requiring you to produce ad hoc collections APIs.
✓ Fosters software reuse by providing a standard interface for collections
and algorithms with which to manipulate them.

Reinforcement Learning 5
Value Prediction with function Approximation

Difficulties:
In many tasks to which we would like to apply
reinforcement learning, most states encountered will
never have been experienced exactly before.
This will almost always be the case when the state or
action spaces include continuous variables or
complex sensations, such as a visual image.
Solution – generalize from previously experienced
states to the ones that have never been seen.

Reinforcement Learning 6
Collections Interface
Why collections?

Collections are used to hold a collection of objects.


List holds objects based on
order of insertion and
can hold non unique collection
Set holds objects
without any order and
are unique
Maps holds objects based on
a key and value pair,
unique key and
no specific order
Hierarchy of Collection Framework

20CS305 ADVANCED JAVA PROGRAMMING UNIT 1 9


Collection Interface
The Collection interface is the interface which is
implemented by all the classes in the collection framework.
It declares the methods that every collection will have.
In other words, we can say that the Collection interface
builds the foundation on which the collection framework
depends.
Some of the methods of Collection interface are Boolean
add(Object obj), Boolean addAll(Collection c), void clear(),
etc. which are implemented by all the sub classes of
Collection interface.
Hierarchy of Collection Framework:
The java.util package contains all the classes and
interfaces for the Collection framework.
20CS305 ADVANCED JAVA PROGRAMMING UNIT 1 10
Collection Interface

20CS305 ADVANCED JAVA PROGRAMMING UNIT 1 11


Methods in Collections Interface
Methods of Collection interface

Sl. No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

It is used to insert the specified collection elements


2 public boolean addAll(Collection<? extends E> c)
in the invoking collection.

3 public boolean remove(Object element) It is used to delete an element from the collection.

It is used to delete all the elements of the specified


4 public boolean removeAll(Collection<?> c)
collection from the invoking collection.

It is used to delete all the elements of the collection


5 default boolean removeIf(Predicate<? super E> filter)
that satisfy the specified predicate.

It returns the total number of elements in the


6 public int size()
collection.
It removes the total number of elements from the
7 public void clear()
collection.
8 public boolean contains(Object element) It is used to search an element.
It is used to search the specified collection in the
9 public boolean containsAll(Collection<?> c)
collection.
10 public Iterator iterator() It returns an iterator.
11 public Object[] toArray() It converts collection into array.
12 public boolean isEmpty() It checks if collection is empty.
13 public boolean equals(Object element) It matches two collections.

13
Iterable and Iterator Interface
Iterable Interface in Java

❑Iterable Interface
❑The Iterable interface is the root interface for all the collection
classes.
❑The Collection interface extends the Iterable interface and
therefore all the subclasses of Collection interface also implement
the Iterable interface.
❑It contains only one abstract method. i.e.,
Iterator<T> iterator()
It returns the iterator over the elements of type T.

15
Iterator Interface
❑Iterator Interface:
❑Iterator is an object that enables you to traverse through a collection.
❑Can be used to remove elements from the collection selectively, if desired.
❑There are only three methods in the Iterator interface.
❑They are:

Sl. No. Method Description

It returns true if the iterator has more elements


1 public boolean hasNext()
otherwise it returns false.

It returns the element and moves the cursor


2 public Object next()
pointer to the next element.

It removes the last elements returned by the


3 public void remove()
iterator. It is less used.
16
List Interface
List Interface

List Interface
❑List interface extends from Collection interface
❑It stores elements in a sequential manner
❑Elements in the list can be accessed or inserted based on their
position
❑Starts with zero based index
❑Can contain duplicate elements
❑An Iterator can be used to access the elements of the List
❑To instantiate the List interface, we must use :
❑List <data-type> list1= new ArrayList();
❑List <data-type> list2 = new LinkedList();
❑List <data-type> list3 = new Vector();
❑List <data-type> list4 = new Stack();

18
List Interface

❑There are various methods in List interface that can be used to


insert, delete, and access the elements from the list.
❑The classes that implement the List interface are given below.
❑Array List
❑Linked List
❑Vector
❑Stack

19
ArrayList
ArrayList

ArrayList:
❑The ArrayList class implements the List interface.
❑It uses a dynamic array to store the duplicate element of
different data types.
❑It is like an array, but there is no size limit. We can add or
remove elements anytime.
❑The ArrayList class maintains the insertion order.
❑The elements stored in the ArrayList class can be randomly
accessed because it works on an index basis.

21
ArrayList

ArrayList:
❑In ArrayList, manipulation is a little bit slower than the
LinkedList in Java because a lot of shifting needs to occur if
any element is removed from the array list.
❑We can not create an array list of the primitive types, such as
int, float, char, etc. It is required to use the required wrapper
class in such cases. For example:
❑ArrayList<int> al = ArrayList<int>(); // Not Valid
❑ArrayList<Integer> al = new ArrayList<Integer>(); // Valid

22
ArrayList

Constructors of ArrayList
Constructor Description
1.ArrayList() It is used to build an empty
array list.

2.ArrayList(Collection<?extends E>c) It is used to build an array


list that is initialized
with the elements of the
collection c.

3.ArrayList(int capacity) It is used to build an array


list that has the
specified initial capacity.

23
ArrayList : Program 1
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Roopa");//Adding object in arraylist
list.add(“Amudha");
list.add("Raji");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} }}

24
Methods of ArrayList

Method Description
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
It is used to fetch the element from the particular position of
E get(int index)
the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
It is used to return the index in this list of the last occurrence
int lastIndexOf(Object o) of the specified element, or -1 if the list does not contain this
element.
It is used to return an array containing all of the elements in
Object[] toArray()
this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

25
Methods of ArrayList

Method Description
It returns true if the list contains the specified
boolean contains(Object o)
element.
It is used to return the index in this list of the first
int indexOf(Object o) occurrence of the specified element, or -1 if the List
does not contain this element.
It is used to remove the element present at the
E remove(int index)
specified position in the list.
It is used to remove the first occurrence of the
boolean remove(Object o)
specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super It is used to remove all the elements from the list
E> filter) that satisfies the given predicate.
protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list
operator) with the specified element.
It is used to replace the specified element in the list,
E set(int index, E element) 26
present at the specified position.
Methods of ArrayList

Method Description
void sort(Comparator<? It is used to sort the elements of the list on the basis of the
super E> c) specified comparator.
List<E> subList(int It is used to fetch all the elements that lies within the
fromIndex, int toIndex) given range.
It is used to return the number of elements present in the
int size()
list.
It is used to trim the capacity of this ArrayList instance to
void trimToSize()
be the list's current size.

27
Java ArrayList Example Programs

//Program1 - //Printing the arraylist object


import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana"); Output – Program1:
list.add("Grapes"); [Mango, Apple, Banana, Grapes]
System.out.println(list); // //Printing the arraylist object
}
}
//Program2 - //Iterating ArrayList using For-each loop
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){ Output - Program2:
ArrayList<String> list=new ArrayList<String>();//Creating arraylist Mango
list.add("Mango");//Adding object in arraylist Apple
list.add("Apple"); Banana
list.add("Banana"); Grapes
list.add("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);
}
} 28
Java ArrayList Example Programs
❑Program3 - //Get and Set ArrayList
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
Output:
al.add("Mango");
Returning element: Apple
al.add("Apple"); Mango
al.add("Banana"); Dates
Banana
al.add("Grapes");
Grapes
//accessing the element
System.out.println("Returning element: "+al.get(1));
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}
29
QUIZ

1. Which of the following classes is not implemented from the Collection


interface?
a. TreeSet
b. HashTable
c. Vector
d. Linked List
2. Which of the following is a class?
a. Collection
b. Collections
3. Which of the following does not accept duplicate values?
a. ArrayList
b. LinkedList
c. TreeSet
d. Vector

30
Java ArrayList Example Programs

❑Program4 - //Sorting ArrayList //Creating a list of numbers


import java.util.*; List<Integer> list2=new
class SortArrayList{ ArrayList<Integer>();
public static void main(String args[]) list2.add(21);
{ list2.add(11);
//Creating a list of fruits list2.add(51);
List<String> list1=new list2.add(1);
ArrayList<String>(); //Sorting the list
list1.add("Mango"); Collections.sort(list2);
list1.add("Apple"); //Traversing list through the for-each
list1.add("Banana"); loop
list1.add("Grapes"); for(Integer number:list2)
//Sorting the list System.out.println(number);
Collections.sort(list1); }
//Traversing list through the for-each } Output:
Sorting numbers...
loop Apple 1
for(String fruit:list1) Banana 11
System.out.println(fruit); Grapes 21
Mango 51
31
User-defined class objects in Java ArrayList
Example Programs

❑Program5 import java.util.*;


class ArrayList5{
class Student{
public static void main(String args[]){
int rollno;
//Creating user-defined class objects
String name;
Student s1=new Student(101,"Sonoo",23);
int age;
Student s2=new Student(102,"Ravi",21);
Student(int rollno,
Student s2=new Student(103,"Hanumat",25);
String name,
//creating arraylist
int age){
ArrayList<Student> al=new ArrayList<Student>();
this.rollno=rollno;
al.add(s1);//adding Student class object
this.name=name;
al.add(s2);
this.age=age;
al.add(s3);
}
//Getting Iterator
}
Iterator itr=al.iterator();
//traversing elements of ArrayList object
Output:
while(itr.hasNext()){
101 Sonoo 23 Student st=(Student)itr.next();
102 Ravi 21 System.out.println(st.rollno+" "+st.name+" "+st.age);
103 Hanumat 25
} } } 32
Java ArrayList example to remove elements
Example Programs

Program8
import java.util.*;
class ArrayList8 {

public static void main(String [] args)


{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
System.out.println("An initial list of elements: "+al);
//Removing specific element from arraylist
al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
33
Java ArrayList example to remove elements
Example Programs
//Creating another arraylist
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
//Adding new elements to arraylist
al.addAll(al2);
System.out.println("Updated list : "+al);
//Removing all the new elements from arraylist
al.removeAll(al2);
System.out.println("After invoking removeAll() method: "+al);
//Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda expression
System.out.println("After invoking removeIf() method: "+al);
//Removing all the elements available in the list
al.clear();
System.out.println("After invoking clear() method: "+al);
}
}

34
Java ArrayList example to remove elements
Example Programs

Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []

35
Iterating Collection Example Programs

import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");

System.out.println("Traversing list through List Iterator:");


//Here, element iterates in reverse order
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious())
{ Output:
String str=list1.previous(); Traversing list through List Iterator:
System.out.println(str); Ajay
} Ravi
Vijay
Ravi
36
Iterating Collection Example Programs

System.out.println("Traversing list through for loop:");


for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}

System.out.println("Traversing list through forEach() method:");


//The forEach() method is a new feature, introduced in Java 8.
list.forEach(a->{ //Here, we are using lambda expression
System.out.println(a); Output:
});
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay 37
Iterating Collection Example Programs

System.out.println("Traversing list through forEachRemaining() method:");


Iterator<String> itr=list.iterator();
itr.forEachRemaining(a-> //Here, we are using lambda expression
{
System.out.println(a);
});
}
}
Output:
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay

38
Java ArrayList example of isEmpty() method
Example Programs
import java.util.*;
class ArrayList10{

public static void main(String [] args)


{
ArrayList<String> al=new ArrayList<String>();
System.out.println("Is ArrayList Empty: "+al.isEmpty());
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After Insertion");
System.out.println("Is ArrayList Empty: "+al.isEmpty());
}
}
Output:
Is ArrayList Empty: true
After Insertion
Is ArrayList Empty: false

39
LinkedList
LinkedList

LinkedList:
❑Java LinkedList class uses a doubly linked list to store the
elements.
❑It provides a linked-list data structure.
❑It inherits the Abstract List class and implements List and
Deque interfaces.
❑Java LinkedList class can contain duplicate elements.
❑Java LinkedList class maintains insertion order.
❑Java LinkedList class is non synchronized.
❑In Java LinkedList class, manipulation is fast because no
shifting needs to occur.
❑Java LinkedList class can be used as a list, stack or queue.

41
Constructors of LinkedList

42
Methods of LinkedList
Method Description
boolean add(E e) It is used to append the specified element to the end of a list.
void add(int index, E It is used to insert the specified element at the specified position
element) index in a list.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection
extends E> c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection
extends E> c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
boolean addAll(int index, It is used to append all the elements in the specified collection,
Collection<? extends E> c) starting at the specified position of the list.
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
void clear() It is used to remove all the elements from a list.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It is used to return true if a list contains a specified element.

43
Methods of LinkedList
Method Description
Iterator<E> It is used to return an iterator over the elements in a deque in
descendingIterator() reverse sequential order.
E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position in a list.

E getFirst() It is used to return the first element in a list.


E getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain any element.
ListIterator<E> It is used to return a list-iterator of the elements in proper
listIterator(int index) sequence, starting at the specified position in the list.
boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E e) It inserts the specified element at the front of a list.
boolean offerLast(E e) It inserts the specified element at the end of a list.
44
Methods of LinkedList
Method Description
E peek() It retrieves the first element of a list
E peekFirst() It retrieves the first element of a list or returns null if a list is
empty.
E peekLast() It retrieves the last element of a list or returns null if a list is
empty.
E poll() It retrieves and removes the first element of a list.
E pollFirst() It retrieves and removes the first element of a list, or returns null
if a list is empty.
E pollLast() It retrieves and removes the last element of a list, or returns null
if a list is empty.
E pop() It pops an element from the stack represented by a list.
void push(E e) It pushes an element onto the stack represented by a list.
E remove() It is used to retrieve and removes the first element of a list.
E remove(int index) It is used to remove the element at the specified position in a list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element
in a list.
45
Methods of LinkedList
Method Description
E removeFirst() It removes and returns the first element from a list.
boolean It is used to remove the first occurrence of the specified
removeFirstOccurrence(O element in a list (when traversing the list from head to tail).
bject o)
E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in a list


removeLastOccurrence(O (when traversing the list from head to tail).
bject o)
E set(int index, E element) It replaces the element at the specified position in a list with
the specified element.
Object[] toArray() It is used to return an array containing all the elements in a list
in proper sequence (from first to the last element).
<T> T[] toArray(T[] a) It returns an array containing all the elements in the proper
sequence (from first to the last element); the runtime type of
the returned array is that of the specified array.
int size() It is used to return the number of elements in a list. 46
Java LinkedList Example Programs

Output:
[Volvo, BMW, Ford, Mazda]
47
Java LinkedList Example Programs

import java.util.*;
public class LinkedList1{
public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
} Output:
} Ravi
Vijay
Ravi
Ajay
48
Java LinkedList to add Elements Example Programs

import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element)
method: "+ll);

49
Java LinkedList to add Elements Example Programs

LinkedList<String> ll2=new LinkedList<String>();


ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E>
c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<?
extends E> c) method: "+ll);

50
Java LinkedList to add Elements Example Programs

//Adding an element at the first position


ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);

} Output:
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
51
Java LinkedList to remove Elements
Example Programs
import java.util.*;
public class LinkedList3 {
Output:
public static void main(String [] args)
{ Initial list of elements: []
LinkedList<String> ll=new LinkedList<String>(); After invoking add(E e) method: [R
ll.add("Ravi"); After invoking add(int index, E elem
ll.add("Vijay"); After invoking addAll(Collection<? e
ll.add("Ajay"); [Ravi, Gaurav, Vijay, Ajay, Sonoo, H
ll.add("Anuj"); After invoking addAll(int index, Coll
ll.add("Gaurav"); [Ravi, John, Rahul, Gaurav, Vijay, A
ll.add("Harsh"); After invoking addFirst(E e) method
ll.add("Virat"); [Lokesh, Ravi, John, Rahul, Gaurav
ll.add("Gaurav"); After invoking addLast(E e) method
ll.add("Harsh"); [Lokesh, Ravi, John, Rahul, Gaurav
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll); 52
Java LinkedList to remove Elements
Example Programs
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);

53
Java LinkedList to remove Elements
Example Programs
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list


ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}

54
Java LinkedList to remove Elements
Example Programs

Output:
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav,
Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav,
Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

55
Java LinkedList to remove Elements
Example Programs
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list


ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}

Page 33

56
Difference Between ArrayList and LinkedList

ArrayList LinkedList
1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked
array to store the elements. list to store the elements.
2) Manipulation with ArrayList Manipulation with LinkedList is faster than
is slow because it internally uses an array. ArrayList because it uses a doubly linked list,
If any element is removed from the array, all so no bit shifting is required in memory.
the other elements are shifted in memory.
3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.
5) The memory location for the elements of The location for the elements of a linked list
an ArrayList is contiguous. is not contagious.
6) Generally, when an ArrayList is initialized, There is no case of default capacity in a
a default capacity of 10 is assigned to the LinkedList. In LinkedList, an empty list is
ArrayList. created when a LinkedList is initialized.
7) To be precise, an ArrayList is a resizable LinkedList implements the doubly linked list
array. of the list interface.
57
Difference Between ArrayList and LinkedList

Points to Ponder
➢ Use List Collection classes if the order in which the element added
matters
➢ Use List when you want to perform insert, delete and update operations
based on particular positions in the list
➢ ArrayList, LinkedList and Vector all of them implement List interface
➢ LinkedList provides a better performance over ArrayList in insertion and
deletion operation.
➢ In case of frequent insertion and deletion operation, the choice can be
LinkedList than ArrayList
➢ Search operations are faster in ArrayList
➢ Both ArrayList and LinkedList are not synchronized
➢ Vector is synchronized
➢ If thread safety is not important, then we should choose either ArrayList
or LinkedList

58
Set Interface
Set Interface

➢ The set is an interface available in the java.util package.


➢ The set interface extends the Collection interface.
➢ An unordered collection or list in which duplicates are not allowed
is referred to as a collection interface.
➢ The set interface is used to create the mathematical set.
➢ The set interface use collection interface's methods to avoid the insertion
of the same elements.
➢ If you add duplicates, it will replace the existing one
➢ It allows you to add only a single null value
➢ Implementation classes for Set are TreeSet, HashSet and
LinkedHashSet
➢ Set can be instantiated as:
Set<data-type> s1=new HashSet<data-type>();
Set<data-type> s2=new LinkedHashSet<data-type>();
Set<data-type> s3=new TreeSet<data-type>();

60
HashSet
HashSet

➢ HashSet class implements Set Interface.


➢ It represents the collection that uses a hash table for storage.
➢ Hashing is used to store the elements in the HashSet. It contains unique items.
➢ No duplicates allowed, unsorted & unordered Set.
➢ HashSet allows null value.
➢ HashSet class is non synchronized.
➢ HashSet doesn’t maintain the insertion order. Here, elements are inserted on the
basis of their hash code.
➢ HashSet is the best approach for search operations.
➢ The initial default capacity of HashSet is 16, and the load factor is 0.75.

62
HashSet

import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator(); Output:
Five
while(i.hasNext()) One
{ Four
System.out.println(i.next()); Two
} Three
} Note: The order of the objects printed
} are not predictable.

63
Constructors in Java HashSet Class

Sl. Constructor Description


No.
1) HashSet() It is used to construct a default HashSet.

2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer
value capacity. The capacity grows automatically as elements are
added to the HashSet.

3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the given integer
loadFactor) value capacity and the specified load factor.

4) HashSet(Collection<? It is used to initialize the hash set by using the elements of the
extends E> c) collection c.

64
Methods in Java HashSet Class
Sl. Modifier & Method Description
No. Type
1) boolean add(E e) It is used to add the specified element to this set if it
is not already present.
2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet
instance: the elements themselves are not cloned.

4) boolean Contains It is used to return true if this set contains the


(Object o) specified element.
5) boolean isEmpty() It is used to return true if this set contains no
elements.
6) Iterator<E> iterator() It is used to return an iterator over the elements in
this set.
7) boolean Remove It is used to remove the specified element from this
(Object o) set if it is present.
8) int size() It is used to return the number of elements in the
set.
9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast
Spliterator over the elements in the set. 65
HashSet Class – Example Program

import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements Output:
Ajay
Iterator<String> itr=set.iterator();
Vijay
while(itr.hasNext()){ Ravi
System.out.println(itr.next());
} Note: HashSet doesn't allow duplicate
} elements.
}
66
HashSet Class – Example Program
Removing Elements
import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);

67
HashSet Class – Example Program
Removing Elements
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
}
Output:
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method:
68
HashSet Class – Example Program
Book
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author,
String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
69
HashSet Class – Example Program
Book
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar",
"BPB",8);
Book b2=new Book(102,"Data Communications & Networking",
"Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);

70
HashSet Class – Example Program
Book
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher
+" "+b.quantity);
}
}
}

Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

71
LinkedHashSet
LinkedHashSet Class

➢ Java LinkedHashSet class contains unique elements only like HashSet.


➢ Java LinkedHashSet class provides all optional set operations and permits
null elements.
➢ Java LinkedHashSet class is non-synchronized.
➢ Java LinkedHashSet class maintains insertion order.

Note: Keeping the insertion order in the LinkedHashset has some additional
costs, both in terms of extra memory and extra CPU cycles. Therefore, if it is
not required to maintain the insertion order, go for the lighter-weight
HashMap or the HashSet instead.

73
LinkedHashSet Class

Constructor Description
HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using


the elements of the collection c.

LinkedHashSet(int It is used to initialize the capacity of the


capacity) linked hash set to the given integer value
capacity.

LinkedHashSet(int It is used to initialize both the capacity and


capacity, float fillRatio) the fill ratio (also called load capacity) of
the hash set from its argument.

74
LinkedHashSet Class – Example Program

import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet<String> set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
Output:
{ One
System.out.println(i.next()); Two
} Three
} Four
} Five
75
LinkedHashSet Class – Example Program
Ignoring Duplicate Elements
import java.util.*;
class LinkedHashSet2{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); Output:
} Ravi
Vijay
} Ajay
}
76
TreeSet
TreeSet Class

•Java TreeSet class contains unique elements only like HashSet.


•Java TreeSet class access and retrieval times are quiet fast.
•Java TreeSet class doesn't allow null element.
•Java TreeSet class is non synchronized.
•Java TreeSet class maintains ascending order.
•Java TreeSet class contains unique elements only like HashSet.
•Java TreeSet class access and retrieval times are quite fast.
•Java TreeSet class doesn't allow null elements.
•Java TreeSet class is non-synchronized.
•Java TreeSet class maintains ascending order.
•The TreeSet can only allow those generic types that are comparable. For
example The Comparable interface is being implemented by the StringBuffer
class.
78
Constructors of TreeSet Class

Constructor Description
TreeSet() It is used to construct an empty tree set that
will be sorted in ascending order according to
the natural order of the tree set.

TreeSet(Collection<? It is used to build a new tree set that contains


extends E> c) the elements of the collection c.

TreeSet(Comparator<? It is used to construct an empty tree set that


super E> comparator) will be sorted according to given comparator.

TreeSet(SortedSet<E> It is used to build a TreeSet that contains the


s) elements of the given SortedSet.

79
Methods of TreeSet Class

Method Description
boolean add(E e) It is used to add the specified element to this set if it is
not already present.
boolean It is used to add all of the elements in the specified
addAll(Collection<? collection to this set.
extends E> c)
E ceiling(E e) It returns the equal or closest greatest element of the
specified element from the set, or null there is no such
element.
Comparator<? super It returns a comparator that arranges elements in order.
E> comparator()
Iterator descendingIt It is used to iterate the elements in descending order.
erator()
NavigableSet descen It returns the elements in reverse order.
dingSet()
E floor(E e) It returns the equal or closest least element of the
specified element from the set, or null there is no such
element.
80
Methods of TreeSet Class

Method Description
SortedSet headSet(E It returns the group of elements that are less than the
toElement) specified element.
NavigableSet headSet( It returns the group of elements that are less than or equal
E toElement, boolean to(if, inclusive is true) the specified element.
inclusive)
E higher(E e) It returns the closest greatest element of the specified
element from the set, or null there is no such element.

Iterator iterator() It is used to iterate the elements in ascending order.

E lower(E e) It returns the closest least element of the specified element


from the set, or null there is no such element.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.

81
Methods of TreeSet Class

Method Description
Spliterator spliterator() It is used to create a late-binding and fail-fast spliterator over
the elements.
NavigableSet subSet(E It returns a set of elements that lie between the given range.
fromElement, boolean
fromInclusive, E toElement,
boolean toInclusive)
SortedSet subSet(E It returns a set of elements that lie between the given range
fromElement, E toElement)) which includes fromElement and excludes toElement.

SortedSet tailSet(E It returns a set of elements that are greater than or equal to
fromElement) the specified element.
NavigableSet tailSet(E It returns a set of elements that are greater than or equal to
fromElement, boolean (if, inclusive is true) the specified element.
inclusive)
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.
82
Methods of TreeSet Class

Method Description

boolean remove(Object o) It is used to remove the specified element from this set
if it is present.

void clear() It is used to remove all of the elements from this set.

Object clone() It returns a shallow copy of this TreeSet instance.

E first() It returns the first (lowest) element currently in this


sorted set.

E last() It returns the last (highest) element currently in this


sorted set.

int size() It returns the number of elements in this set.

83
TreeSet Class – Example Program

import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} Output:
} Ajay
} Ravi
Vijay

84
TreeSet Class – Example Program

import java.util.*;
class TreeSet2{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
System.out.println("Traversing element through
Iterator in descending order");
Iterator i=set.descendingIterator(); Output:
while(i.hasNext()) Traversing element through Iterator in
{ descending order
System.out.println(i.next()); Vijay
Ravi
}
Ajay
Traversing element through
} NavigableSet in descending order
} Vijay
Ravi
85
Ajay
TreeSet Class – Example Program

import java.util.*;
class TreeSet3{
public static void main(String args[]){
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Lowest Value: "+set.pollFirst());
System.out.println("Highest Value: "+set.pollLast());
}
} Output:
Lowest Value: 12
Highest Value: 66

86
TreeSet Class – Example Program

import java.util.*;
class TreeSet4{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>(); Output:
set.add("A"); Initial Set: [A, B, C, D, E]
set.add("B"); Reverse Set: [E, D, C, B, A]
set.add("C"); Head Set: [A, B, C]
set.add("D"); SubSet: [B, C, D, E]
set.add("E"); TailSet: [D, E]
System.out.println("Initial Set: "+set);
System.out.println("Reverse Set: "+set.descendingSet());
System.out.println("Head Set: "+set.headSet("C", true));
System.out.println("SubSet: "+set.subSet("A", false, "E", true));
System.out.println("TailSet: "+set.tailSet("C", false));
}
}

87
TreeSet Class – Example Program

import java.util.*;
class TreeSet5{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
Output:
set.add("A");
Intial Set: [A, B, C, D, E]
set.add("B"); Head Set: [A, B]
set.add("C"); SubSet: [A, B, C, D]
set.add("D"); TailSet: [C, D, E]
set.add("E");
System.out.println("Intial Set: "+set);
System.out.println("Head Set: "+set.headSet("C"));
System.out.println("SubSet: "+set.subSet("A", "E"));
System.out.println("TailSet: "+set.tailSet("C"));
}
}

88
TreeSet Class – Example Program

import java.util.*;
class Book implements Comparable<
Book>{ // implementing the abstract method
int id; public int compareTo(Book b) {
String name,author,publisher; if(id>b.id){
int quantity; return 1;
public Book(int id, String name, Strin }else if(id<b.id){
g author, String publisher, int quantity) return -1;
{ }else{
this.id = id; return 0;
this.name = name; }
this.author = author; }
this.publisher = publisher; }
this.quantity = quantity;
}

89
TreeSet Class – Example Program

public class TreeSetExample {


public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar",
"BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking",
"Forouzan","Mc Graw Hill",4);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" “
Output: +b.publisher+" "+b.quantity);
} 101 Data Communications & Networking Forouzan Mc Graw Hill 4
} 121 Let us C Yashwant Kanetkar BPB 8
} 233 Operating System Galvin Wiley 6
90
ClassCastException in TreeSet Class
Example Program
// important import statement // setting the name of the
import java.util.*; //employee
void setName(String name)
class Employee {
{ this.name = name;
}
int empId;
String name; // setting the employee id
// of the employee
// getting the name of the employee void setId(int a)
String getName() { this.empId = a; }
{
return this.name; // retrieving the employee id of
} // the employee
int getId()
{ return this.empId; }

} 91
ClassCastException in TreeSet Class
Example Program
public class ClassCastExceptionTreeSet
{

// main method
public static void main(String[] argvs)
{
// creating objects of the class Employee
Employee obj1 = new Employee();

Employee obj2 = new Employee();

TreeSet<Employee> ts = new TreeSet<Employee>();

// adding the employee objects to


// the TreeSet class
ts.add(obj1);
ts.add(obj2);

System.out.println("The program has been executed suc


cessfully.");

}
} 92
ClassCastException in TreeSet Class
Example Program
When we compile the above program, we get the ClassCastException, as shown
below.

Exception in thread "main" java.lang.ClassCastException: class Employee cannot


be cast to class java.lang.Comparable (Employee is in unnamed module of loader
'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.TreeMap.compare(TreeMap.java:1569)
at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776)
at java.base/java.util.TreeMap.put(TreeMap.java:785)
at java.base/java.util.TreeMap.put(TreeMap.java:534)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at ClassCastExceptionTreeSet.main(ClassCastExceptionTreeSet.java:52)

In the above program, it is required to implement a Comparable interface. It is


because the TreeSet maintains the sorting order, and for doing the sorting the
comparison of different objects that are being inserted in the TreeSet is must,
which is accomplished by implementing the Comparable interface.

93
Comparable Interface
Comparable Interface

➢ Java Comparable interface is used to order the objects of the user-defined


class.
➢ This interface is found in java.lang package and contains only one method
named compareTo(Object).
➢ It provides a single sorting sequence only, i.e., you can sort the elements
on the basis of single data member only.
➢ For example, it may be rollno, name, age or anything else.
compareTo(Object obj) method

public int compareTo(Object obj)


➢ It is used to compare the current object with the specified object.
➢ It returns
➢ positive integer, if the current object is greater than the specified
object.
➢ negative integer, if the current object is less than the specified
object.
➢ zero, if the current object is equal to the specified object.
95
Comparable Interface – Example Program
//student.java
class Student implements Comparable<Student>{
int rollno;
String name;
int age;

Student(int rollno,String name,int age){


this.rollno=rollno;
this.name=name;
this.age=age;
}

public int compareTo(Student st){


if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
} 96
Comparable Interface – Example Program

//test.java
import java.util.*;
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
} Output:
} 105 Jai 21
101 Vijay 23
106 Ajay 27
97
Map Interface
Map Interface

•Map is an interface that stores data in the form of key value pair.
•All the keys in the map will be unique.
•We can retrieve the value stored in a map by providing the key value.
•A Map cannot contain duplicate values.
•Each key can map to atmost one value. There are two interfaces for
implementing Map in java :Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap.
•A Map doesn't allow duplicate keys, but you can have duplicate values.
HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't
allow any null key or value.
•A Map can't be traversed, so you need to convert it into Set using keySet() or
entrySet() method.
99
Map Interface

Class Description
HashMap HashMap is the implementation of Map, but it doesn't
maintain any order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits
HashMap class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It
maintains ascending order.

100
Map Interface

Method Description
V put(Object key, It is used to insert an entry in the map.
Object value)
void putAll(Map It is used to insert the specified map in the map.
map)
V putIfAbsent(K key, It inserts the specified value with the specified key in the
V value) map only if it is not already specified.

V remove(Object It is used to delete an entry for the specified key.


key)
boolean It removes the specified values with the associated specified
remove(Object key, keys from the map.
Object value)
Set keySet() It returns the Set view containing all the keys.

Set<Map.Entry<K,V It returns the Set view containing all the keys and values.
>> entrySet()
void clear() It is used to reset the map. 101
Map Interface

Method Description
V compute(K key, It is used to compute a mapping for the specified key and its
BiFunction<? super K,? current mapped value (or null if there is no current mapping).
super V,? extends V>
remappingFunction)
boolean This method returns true if some value equal to the value
containsValue(Object exists within the map, else return false.
value)
boolean This method returns true if some key equal to the key exists
containsKey(Object key) within the map, else return false.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void It performs the given action for each entry in the map until all
forEach(BiConsumer<? entries have been processed or the action throws an
super K,? super V> exception.
action)
V get(Object key) This method returns the object that contains the value
associated with the key. 102
Map Interface
Method Description
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty; returns false if
it contains at least one key.
V merge(K key, V value, If the specified key is not already associated with a value or is
BiFunction<? super V,? associated with null, associates it with the given non-null
super V,? extends V> value.
remappingFunction)
V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V It replaces the old value with the new value for a specified
oldValue, V newValue) key.
void It replaces each entry's value with the result of invoking the
replaceAll(BiFunction<? given function on that entry until all entries have been
super K,? super V,? processed or the function throws an exception.
extends V> function)
Collection values() It returns a collection view of the values contained in the
map.
int size() This method returns the number of entries in the map. 103
Map.Entry Interface

• Entry is the subinterface of Map. So we will be accessed it by Map.Entry


name.
• It returns a collection-view of the map, whose elements are of this class.
It provides methods to get key and value.
Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value corresponding to this
entry with the specified value.
boolean equals(Object o) It is used to compare the specified object with the
other existing objects.
static <K extends It returns a comparator that compare the objects in
Comparable<? super natural order on key.
K>,V>
Comparator<Map.Entry<K
,V>> comparingByKey() 104
Map.Entry Interface

Method Description
static <K extends Comparable<? It returns a comparator that compare the
super K>,V> objects in natural order on key.
Comparator<Map.Entry<K,V>>
comparingByKey()
static <K,V> It returns a comparator that compare the
Comparator<Map.Entry<K,V>> objects by key using the given Comparator.
comparingByKey(Comparator<?
super K> cmp)
static <K,V extends Comparable<? It returns a comparator that compare the
super V>> objects in natural order on value.
Comparator<Map.Entry<K,V>>
comparingByValue()
static <K,V> It returns a comparator that compare the
Comparator<Map.Entry<K,V>> objects by value using the given Comparator.
comparingByValue(Comparator<?
super V> cmp)
105
Java Map Example: Non-Generic (Old Style)

//Non-generic
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
Output:
//Adding elements to map 1 Amit
map.put(1,"Amit"); 2 Jai
map.put(5,"Rahul");
map.put(2,"Jai");
5 Rahul
map.put(6,"Amit"); 6 Amit
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
106
Java Map Example: Generic (New Style)

import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} Output:
} 102 Rahul
100 Amit
101 Vijay

107
Java Map Example: comparingByKey()

import java.util.*;
class MapExample3{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey()) Output:
//Performs an action for each element of this stream
.forEach(System.out::println); 100=Amit
} 101=Vijay
} 102=Rahul

108
Java Map Example: comparingByKey()
in Descending Order
import java.util.*;
class MapExample4{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
} Output:
} 102=Rahul
101=Vijay
100=Amit 109
Java Map Example: comparingByValue()

import java.util.*;
class MapExample5{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByValue())
//Performs an action for each element of this stream
.forEach(System.out::println); Output:
} 100=Amit
}
102=Rahul
101=Vijay 110
HashMap Class
HashMap Class

➢ HashMap uses the hashcode value of an object to determine how the object
should be stored in the collection.
➢ Hashcode is used again to help locate the object in the collection.
➢ Gives you an unsorted and unordered Map.
➢ Allows one null key and multiple null values in a collection.
➢ HashMap are not synchronized
➢ Map is an object that stores key/value pairs. Given a key, you can find its value.
➢ Keys must be unique, but values may be duplicated.
➢ The HashMap class provides the primary implementation of the map interface.
➢ The HashMap class uses a hashtable to implement Map interface.
➢ This allows the execution time of basic operations, such as get() and put() to
be constant.

112
Java HashMap Example: No Duplicate Key

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(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());
} Output:
} Iterating Hashmap...
} 1 Grapes
2 Apple
3 Banana 113
Java HashMap Example: add() elements

import java.util.*;
class HashMap1{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
System.out.println("Initial list of elements: "+hm);
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

System.out.println("After invoking put() method ");


for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
Output:
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana 114
Java HashMap Example: add() elements

hm.putIfAbsent(103, "Gaurav");
System.out.println("After invoking putIfAbsent() method ");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

115
Java HashMap Example: add() elements

Output:
Initial list of elements: {}
After invoking put() method
100 Amit
101 Vijay
102 Rahul
After invoking putIfAbsent() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
After invoking putAll() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
116
Java HashMap Example: to remove() elements
import java.util.*;
public class HashMap2 {
public static void main(String args[]) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(103, "Gaurav");
System.out.println("Initial list of elements: "+map);
//key-based removal
map.remove(100);
System.out.println("Updated list of elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Updated list of elements: "+map);
//key-value pair based removal
map.remove(102, "Rahul");
System.out.println("Updated list of elements: "+map);
}
} 117
Java HashMap Example: to remove() elements
Output:

Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav}


Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {102=Rahul, 103=Gaurav}
Updated list of elements: {103=Gaurav}

118
Java HashMap Example: to replace() elements

import java.util.*;
class HashMap3{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
System.out.println("Initial list of elements:");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}

119
Java HashMap Example: to replace() elements
System.out.println("Updated list of elements:");
hm.replace(102, "Gaurav");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(101, "Vijay", "Ravi");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replaceAll((k,v) -> "Ajay");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
} 120
Java HashMap Example: to replace() elements
Output:
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay

121
Java HashMap Example: Book

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int q
uantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}

122
Java HashMap Example: Book

public class MapExample {


public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new HashMap<Integer,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking",


"Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to map


map.put(1,b1);
map.put(2,b2);
map.put(3,b3);

123
Java HashMap Example: Book

//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+
b.publisher+" "+b.quantity);
}
}
} Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications and Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
124
LinkedHashMap Class
LinkedHashMap Class

➢ Java LinkedHashMap class is Hashtable and Linked list implementation of the


Map interface, with predictable iteration order. It inherits HashMap class and
implements the Map interface.
➢ Java LinkedHashMap contains values based on the key.
➢ Java LinkedHashMap contains unique elements.
➢ Java LinkedHashMap may have one null key and multiple null values.
➢ Java LinkedHashMap is non synchronized.
➢ Java LinkedHashMap maintains insertion order.
➢ The initial default capacity of Java HashMap class is 16 with a load factor of
0.75.

126
Java LinkedHashMap Example

import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){

LinkedHashMap<Integer,String> hm
=new LinkedHashMap<Integer,String>();

hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} Output:
} 100 Amit
101 Vijay
102 Rahul
127
Java LinkedHashMap Example – Key-Value Pair

import java.util.*;
class LinkedHashMap2{
public static void main(String args[]){
LinkedHashMap<Integer, String> map =
new LinkedHashMap<Integer, String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Fetching key
System.out.println("Keys: "+map.keySet());
//Fetching value
System.out.println("Values: "+map.values());
//Fetching key-value pair
System.out.println("Key-Value pairs: "+map.entrySet());
} Output:
} Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul] 128
Java LinkedHashMap Example – remove()

import java.util.*;
public class LinkedHashMap3 {
public static void main(String args[]) {
Map<Integer,String> map
=new LinkedHashMap<Integer,String>();
map.put(101,"Amit");
map.put(102,"Vijay");
map.put(103,"Rahul");
System.out.println("Before invoking remove() method: "+map);

map.remove(102);
System.out.println("After invoking remove() method: "+map);
}
}
Output:
Before invoking remove() method: {101=Amit, 102=Vijay,
103=Rahul}
After invoking remove() method: {101=Amit, 103=Rahul}
129
Java LinkedHashMap Example – Book

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int q
uantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}

130
Java LinkedHashMap Example – Book

public class MapExample {


public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();

//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Fo


rouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to map


map.put(2,b2);
map.put(1,b1);
map.put(3,b3);

131
Java LinkedHashMap Example – Book

//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+
b.publisher+" "+b.quantity);
}
}
}
Output:
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6
132
HashTable Class
HashTable Class

➢ Java Hashtable class implements a hashtable, which maps keys to values. It


inherits Dictionary class and implements the Map interface.
➢ A Hashtable is an array of a list. Each list is known as a bucket. The position of
the bucket is identified by calling the hashcode() method. A Hashtable contains
values based on the key.
➢ Java Hashtable class contains unique elements.
➢ Java Hashtable class doesn't allow null key or value.
➢ Java Hashtable class is synchronized.
➢ The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

134
Java HashTable Example

import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} Output:
} 103 Rahul
102 Ravi
101 Vijay
100 Amit
135
TreeMap Class
TreeMap Class

➢ Java TreeMap class is a red-black tree based implementation. It provides an


efficient means of storing key-value pairs in sorted order.
➢ 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.

137
Java TreeMap Example

import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");

for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
} Output:
100 Amit
101 Vijay
102 Ravi
103 Rahul
138
Properties Class
Properties Class

➢ The Properties class represents a persistent set of properties. The Properties can
be saved to a stream or loaded from a stream. It belongs
to java.util package. Properties define the following instance variable. This
variable holds a default property list associated with a Properties object.
➢ Properties is a subclass of Hashtable.
➢ It is used to maintain a list of values in which the key is a string and the value is
also a string i.e; it can be used to store and retrieve string type data from the
properties file.
➢ Properties class can specify other properties list as it’s the default. If a particular
key property is not present in the original Properties list, the default properties
will be searched.
➢ Properties object does not require external synchronization and Multiple threads
can share a single Properties object. Also, it can be used to retrieve the
properties of the system. 140
Properties Class - Constructors

1. Properties(): This creates a Properties object that has no default values.

Properties p = new Properties();

2. Properties(Properties propDefault): The second creates an object that uses


propDefault for its default value.

Properties p = new Properties(Properties propDefault);

141
Example of Properties class to get all the system
properties
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = “ +entry.getValue());
} }} Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD 142
Queue Interface
Queue Interface

➢ The interface Queue is available in the java.util package and does extend the
Collection interface.
➢ It is used to keep the elements that are processed in the First In First Out (FIFO)
manner.
➢ It is an ordered list of objects, where insertion of elements occurs at the end of
the list, and removal of elements occur at the beginning of the list.
➢ Being an interface, the queue requires, for the declaration, a concrete class, and
the most common classes are the LinkedList and PriorityQueue in Java.
➢ Implementations done by these classes are not thread safe.
➢ If it is required to have a thread safe implementation, PriorityBlockingQueue is an
available option.

144
Queue Interface - Features

➢ 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.
➢ PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that
are used most frequently.
➢ The NullPointerException is raised, if any null operation is done on the
BlockingQueues.
➢ Those Queues that are present in the util package are known as Unbounded
Queues.
➢ Those 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. 145
Methods in Queue Interface

Method Description
boolean It is used to insert the specified element into this
add(object) queue and return true upon success.
boolean It is used to insert the specified element into this
offer(object) queue.
Object It is used to retrieves and removes the head of this
remove() queue.
Object poll() It is used to retrieves and removes the head of this
queue, or returns null if this queue is empty.

Object It is used to retrieves, but does not remove, the head


element() of this queue.
Object peek() It is used to retrieves, but does not remove, the head
of this queue, or returns null if this queue is empty.

146
PriorityQueue Class
PriorityQueue Class

➢ PriorityQueue is also class that is defined in the collection framework that gives
us a way for processing the objects on the basis of priority.
➢ Insertion and deletion of objects follows FIFO pattern in the Java queue.
➢ However, sometimes the elements of the queue are needed to be processed
according to the priority, that's where a PriorityQueue comes into action.

148
Java PriorityQueue Example

import java.util.*; queue.remove();


class TestCollection12{ queue.poll();
public static void main(String args[]){ System.out.println("after
PriorityQueue<String> queue removing two elements:");
=new PriorityQueue<String>(); Iterator<String> itr2
queue.add("Amit"); =queue.iterator();
queue.add("Vijay"); while(itr2.hasNext()){
queue.add("Karan"); System.out.println(itr2.next());
queue.add("Jai");
queue.add("Rahul"); }
System.out.println("head:"+queue.element()); }
System.out.println("head:"+queue.peek()); }
System.out.println("iterating the
queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
149
Java PriorityQueue Example

Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

150
DeQueue Interface
DeQueue Interface - Features

➢ The interface called Deque is present in java.util package.


➢ It is the sub type of the interface queue.
➢ The Deque supports the addition as well as the removal of elements from both
ends of the data structure.
➢ Therefore, a deque can be used as a stack or a queue. We know that the stack
supports the Last In First Out(LIFO)operation, and the operation First In First Out
is supported by a queue. As a deque supports both, either of the mentioned
operations can be performed on it. Deque is an acronym for "double ended
queue".

152
DeQueue Interface - Methods

Methods Description
add(E e) This method is used to insert a specified element into
the queue represented by the deque
addAll(Collection<? Adds all the elements in the specified collection at the
Extends E>c) end of the deque.
addFirst(E e) Inserts the specified element at the front of the deque.
addLast(E e) Inserts the specified element at the end of the deque.
contains(object o) Returns true if the deque contains the specified
element.
descendingIterator() Returns an iterator over the elements in reverse
sequential order.
element() Retrieves the head of the queue represented by the
deque.
getFirst() Retrieves but does not remove the first element of the
deque.
getLast() Retrieves but does not remove the last element of the
deque.
153
DeQueue Interface - Methods

Methods Description
iterator() Returns an iterator over the element in the deque in a
proper sequence.
offer(E e) Inserts the specified element into the deque, returning
true upon success and false if no space is available.
offerFirst() Inserts the specified element at the front of the deque
unless it violates the capacity restriction.
offerLast() Inserts the specified element at the end of the deque
unless it violates the capacity restriction.
peek() Retrieves but does not move the head of the queue
represented by the deque or may return null if the
deque is empty.
peekFirst() Retrieves but does not move the first element of the
deque or may return null if the deque is empty.
peekLast() Retrieves but does not move the last element of the
deque or may return null if the deque is empty.
154
DeQueue Interface - Methods

Methods Description
poll() Retrieves and remove the head of the queue
represented by the deque or may return null if the
deque is empty.
pollFirst() Retrieves and remove the first element of the deque or
may return null if the deque is empty.
pollLast() Retrieves and remove the last element of the deque or
may return null if the deque is empty.
pop() Pops an element from the stack represented by the
deque.
push() Pushes an element onto the stack represented by the
deque.
remove() Retrieves and remove the head of the queue
represented by the deque.
removeLastOccurre Remove the last occurrence of the element from the
nce(Object o) deque. 155
DeQueue Interface - Methods

Methods Description
removeLast() Retrieve and remove the last element from the deque.
removeLastOccurre Remove the last occurrence of the element from the
nce(Object o) deque.
size() Returns the total number of elements in the deque.

156
ArrayDeque Class
ArrayDeque Class

➢ It is not possible to create an object of an interface in Java. Therefore, for


instantiation, a class that implements the Deque interface is required and that
class is ArrayDeque.
➢ Unlike Queue, we can add or remove elements from both sides.
➢ Null elements are not allowed in the ArrayDeque.
➢ ArrayDeque is not thread safe, in the absence of external synchronization.
➢ ArrayDeque has no capacity restrictions.
➢ ArrayDeque is faster than LinkedList and Stack.

158
ArrayDeque Class - Example

import java.util.*;
public class ArrayDequeExample{
public static void main(String[] args){
//Creating Deque and adding elements
Deque<String> deque=new ArrayDeque<String>();
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for(String str:deque){ Output:
System.out.println(str); Ravi
} Vijay
} Ajay
}
159
ArrayDeque Class – Example
offerFirst(), pollLast()
Import java.util.*;
Public class DequeExample{
Public static void main(String[] args){
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){ Output:
System.out.println(s); After offerFirst Traversal...
} jai
deque.pollLast(); arvind
System.out.println("After pollLast() Traversal..."); vimal
for(String s:deque){ mukul
System.out.println(s); After pollLast() Traversal...
} jai
} arvind
} Vimal
160
Utility Class
Utility Class

➢ A utility class in Java is a class that provides static methods that are accessible
for use across an application. The static methods in utility classes are used for
performing common routines in our application.
➢ Utility classes cannot be instantiated and are sometimes stateless without static
variables. We declare a utility class as final, and all its methods must be static.
➢ Since we don’t want our utility classes to be instantiated, a private constructor
is introduced. Having a private constructor means that Java won’t create a
default constructor for our utility class. The constructor can be empty.
➢ The purpose of a utility class is to provide methods for executing certain
functionalities within a program, while the main class focuses on the core
problem it solves.
➢ Methods of a utility are accessed via the classname. It makes our code more
flexible for use while remaining modular.
162
Utility Class

➢ Java has utility classes such as java.util.Arrays, java.lang.Math,


java.util.Scanner, java.util.Collections, etc.

How to Create a Java Utility Class


➢ Creating a utility class is not so different from how we create a helper class. A
few things are done a little differently when creating a utility class.
➢ To create a utility class, we use a public access modifier and also declare the
class as final. The final key word used when creating utility classes means that
the class would remain unchangeable. It cannot be inherited or instantiated.
➢ Another rule to observe is that all methods of a utility class are static, with a
public access modifier.
➢ Since we have only static methods within utility classes, these methods can
only be accessed via the class name.

163
Create Utility Class - Example

public final class MyUtilityClass{


private MyUtilityClass(){}
public static String returnUpperCase(String stringInput){
return stringInput.toUpperCase();
}

public static String returnLowerCase(String stringInput){


return stringInput.toLowerCase();
}
public static String[] splitStringInput(String stringInput,
String delimiter){
return stringInput.split(delimiter);
}
}

164
THANK YOU
https://www.javatpoint.com/java-deque

Page 70

You might also like