0% found this document useful (0 votes)
16 views46 pages

UNIT 4 Part1

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as List, Set, and Map. It explains key components like the Collection interface, its methods, and implementations like ArrayList, LinkedList, Vector, and Stack, along with their functionalities. Additionally, it covers important concepts such as iterators, sorting, and the use of Comparable and Comparator interfaces.

Uploaded by

aarya2312022
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)
16 views46 pages

UNIT 4 Part1

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as List, Set, and Map. It explains key components like the Collection interface, its methods, and implementations like ArrayList, LinkedList, Vector, and Stack, along with their functionalities. Additionally, it covers important concepts such as iterators, sorting, and the use of Comparable and Comparator interfaces.

Uploaded by

aarya2312022
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/ 46

UNIT 4: Java Collections Framework: Collection in Java, Collection

Framework in Java, Hierarchy of Collection Framework, Iterator


Interface, Collection Interface, List Interface, ArrayList, LinkedList,
Vector, Stack, Queue Interface, Set Interface, HashSet, LinkedHashSet,
SortedSet Interface, TreeSet, Map Interface, HashMap Class,
LinkedHashMap Class, TreeMap Class, Hashtable Class, Sorting,
Comparable Interface, Comparator Interface, Properties Class in Java.
Collection in Java
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of objects.
• Java Collections can achieve all the operations that you
perform on a data such as searching, sorting, insertion,
manipulation, and deletion.
What is a framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
• What is Collection framework
• The Collection framework represents a unified
architecture for storing and manipulating a
group of objects. It has: Interfaces and I
implementations, i.e., classes, Algorithm
Hierarchy of Collection Framework
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.
Hierarchy of Collection Framework

• Let us see the hierarchy of Collection


framework. The java.util package contains all
the classes and interfaces for the Collection
framework.
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.
• 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 subclasses of
Collection interface.
Collection interface methods
Method Description
This method is used to add an object to the
add(Object)
collection.
This method adds all the elements in the given
addAll(Collection c)
collection to this collection.
This method removes all of the elements from this
clear()
collection.
This method returns true if the collection contains
contains(Object o)
the specified element.
This method returns true if the collection contains
containsAll(Collection c)
all of the elements in the given collection.
This method compares the specified object with
equals(Object o)
this collection for equality.
This method is used to return the hash code value
hashCode()
for this collection.
This method returns true if this collection contains
isEmpty()
no elements.
This method returns an iterator over the elements
iterator()
in this collection.
max() This method is used to return the maximum value
remove(Object o)
This method is used to remove the given object from the collection. If there are
duplicate values, then this method removes the first occurrence of the object.
removeAll(Collection c)
This method is used to remove all the objects mentioned in the given collection from the
collection.
removeIf(Predicate filter)
This method is used to remove all the elements of this collection that satisfy the
given predicate.
retainAll(Collection c)
This method is used to retain only the elements in this collection that are contained in
the specified collection.
size()
This method is used to return the number of elements in the collection.
spliterator()
This method is used to create a Spliterator over the elements in this collection.
stream()
This method is used to return a sequential Stream with this collection as its source.
toArray()
This method is used to return an array containing all of the elements in this collection.
List Interface
List interface is the child interface of Collection interface. It
inhibits a list type data structure in which we can store the
ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList,
Vector, and Stack.

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();
There are various methods in List interface that can be used to
insert, delete, and access the elements from the list.


The classes which implement the List
interface are as follows:
• ArrayList
• The ArrayList class implements the List
interface. It uses a dynamic array to store the
duplicate element of different data types. The
ArrayList class maintains the insertion order
and is non-synchronized.
• The elements stored in the ArrayList class can
be randomly accessed. Consider the following
example.
Example ArrayList(adding elements and deleting

// Java program to demonstrate the // Printing elements


// working of ArrayList System.out.println(al);
import java.io.*;
import java.util.*; // Remove element at index 3
al.remove(3);
class GFG {
// Main Method // Displaying the ArrayList
public static void main(String[] args) // after deletion
{ System.out.println(al);
// Declaring the ArrayList with
// initial size n // Printing elements one by one
ArrayList<Integer> al = new for (int i = 0; i < al.size(); i++)
ArrayList<Integer>(); System.out.print(al.get(i) + " ");
}
// Appending new elements at }
// the end of the list
for (int i = 1; i <= 5; i++)
al.add(i);
Output:

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
LinkedList

• LinkedList implements the Collection


interface. It uses a doubly linked list internally
to store the elements.
• It can store the duplicate elements. It
maintains the insertion order and is not
synchronized. In LinkedList, the manipulation
is fast because no shifting is required.
// Java Program to iterate over LinkedList
// Using simple for loop

// Importing all classes of


// java.util package
import java.util.*;
// CLass
class GFG {
// Main driver method
public static void main(String args[])
{ // Creating a ArrayList
LinkedList<String> myList = new LinkedList<String>();

// Adding elements to the list


// Custom inputs
myList.add("A");
myList.add("B");
myList.add("D");
myList.add("D");//storing duplicate elements

// For loop for iterating over the List


for (int i = 0; i < myList.size(); i++) {

// Print all elements of List


System.out.println(myList.get(i));
}}}
Output
Java LinkedList Example to reverse a list of elements
import java.util.*;
public class LinkedList4{
public static void main(String args[]){

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


ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
//Traversing the list of elements in reverse order
Iterator i=ll.descendingIterator(); //arrange list in descending order
while(i.hasNext())
{
System.out.println(i.next());
}

}
}
Output:
Ajay
Vijay
Ravi
Vector
• Definition:
– Vector is a synchronized, resizable array implementation of the List interface.
– It is part of the Java Collections Framework and is found in the java.util package.
• Synchronization:
– Vector is synchronized, meaning it is thread-safe and can be used in multi-threaded
environments without additional synchronization.
– This synchronization can lead to performance overhead, making it slower than
non-synchronized alternatives like ArrayList in single-threaded scenarios.
• Usage:
– Vector is generally used when a thread-safe implementation of a dynamically resizable array
is required.
• Methods:
– Provides all the standard List operations such as adding, removing, and accessing elements.
– Methods like add, remove, and get are synchronized.
SN Method
VECTOR METHODS
Description
1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to the end
of this Vector.
3) addElement() It is used to append the specified component to the end of this vector. It
increases the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.


7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the specified
collection.
9) copyInto() It is used to copy the components of the vector into the specified array.

10) elementAt() It is used to get the component at the specified index.


11) elements() It returns an enumeration of the components of a vector.
12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It ensures that the
vector can hold at least the number of components specified by the minimum capacity
argument.
13) equals() It is used to compare the specified object with the vector for equality.
14) firstElement() It is used to get the first component of the vector.
15) forEach() It is used to perform the given action for each element of the Iterable until all elements have
been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.
17) hashCode() It is used to get the hash code value of a vector.
18) indexOf() It is used to get the index of the first occurrence of the specified element in the vector. It
returns -1 if the vector does not contain the element.
19) insertElementAt() It is used to insert the specified object as a component in the given vector at the specified
index.
20) isEmpty() It is used to check if this vector has no components.
21) iterator() It is used to get an iterator over the elements in the list in proper sequence.
22) lastElement() It is used to get the last component of the vector.
23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the vector. It
returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.
25) remove() It is used to remove the specified element from the vector. If the vector does not contain the
element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are present in the specified collection.
27) removeAllElemen It is used to remove all elements from the vector and set the size of the vector to zero.
ts()
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from the vector.
29) removeElementAt It is used to delete the component at the specified index.
()
import java.util.Vector;
// Checking if an element exists
if (vector.contains("Banana")) {
public class VectorExample {
System.out.println("Vector contains Banana");
public static void main(String[] args) {
} else {
// Creating a Vector of Strings
System.out.println("Vector does not contain Banana");
Vector<String> vector = new Vector<>();
}
// Removing an element
// Adding elements to the Vector
vector.remove("Orange");
vector.add("Apple");
System.out.println("After removing Orange, elements in
vector.add("Banana"); the Vector:");
vector.add("Orange"); for (String fruit : vector) {
System.out.println(fruit);
// Accessing elements using indexes } // Checking the size of the Vector
System.out.println("Element at index 0: " + System.out.println("Size of the Vector: " + vector.size());
vector.get(0));
System.out.println("Element at index 1: " +
// Checking if the Vector is empty
vector.get(1));
if (vector.isEmpty()) {
System.out.println("Element at index 2: " +
vector.get(2)); System.out.println("Vector is empty");
} else {
// Iterating through the Vector System.out.println("Vector is not empty");
System.out.println("Elements in the Vector:"); } // Clearing the Vector
for (String fruit : vector) { vector.clear();
System.out.println(fruit); System.out.println("After clearing, size of the Vector: " +
vector.size()); }
}
}
Output
STACK
Creating a Stack
• If we want to create a stack, first, import
the java.util package and create an object of the
Stack class.
• Stack stk = new Stack();
• Or
• Stack<type> stk = new Stack<>();
• Where type denotes the type of stack like Integer,
String, etc
Methods of the Stack Class
We can perform push, pop, peek and search operation on the stack.
The Java Stack class provides mainly five methods to perform these operations.
Along with this, it also provides all the methods of the Java Vector class.

Method Modifier and Method Description


Type

empty() boolean The method checks the stack is empty


or not.

push(E item) E The method pushes (insert) an


element onto the top of the stack.

pop() E The method removes an element from


the top of the stack and returns the
same element as the value of that
function.

peek() E The method looks at the top element


of the stack without removing it.

search(Object o) int The method searches the specified


object and returns the position of the
object.
Stack Class push() Method
The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to be
pushed into the stack.
Syntax
public E push(E item)
Parameter: An item to be pushed onto the top of the stack.
Returns: The method returns the argument that we have passed as a parameter.
Stack Class pop() Method
The method removes an object at the top of the stack and returns the same object. It
throws EmptyStackException if the stack is empty.
Syntax
public E pop()
Returns: It returns an object that is at the top of the stack.
Let's implement the stack in a Java program and perform push and pop operations.
STACK PUSH AND POP OPERATIONS
import java.util.*; //performing push operation
public class StackPushPopExample static void pushelmnt(Stack stk, int x)
{ public static void main(String args[]) { //invoking push() method
{ //creating an object of Stack class stk.push(new Integer(x));
Stack <Integer> stk = new Stack<>(); System.out.println("push -> " + x);
System.out.println("stack: " + stk); //prints modified stack
//pushing elements into the stack System.out.println("stack: " + stk);
pushelmnt(stk, 20); } //performing pop operation
pushelmnt(stk, 13); static void popelmnt(Stack stk)
pushelmnt(stk, 89); { System.out.print("pop -> ");
pushelmnt(stk, 90); //invoking pop() method
//popping elements from the stack Integer x = (Integer) stk.pop();
popelmnt(stk); System.out.println(x);
popelmnt(stk); //prints modified stack
//throws exception if the stack is empty try { System.out.println("stack: " + stk);
popelmnt(stk); } }
}
catch (EmptyStackException e)
{ System.out.println("empty stack");
}
}
OUTPUT
Stack Class empty() Method

• The empty() method of the Stack class check the stack is empty or
not. If the stack is empty, it returns true, else returns false. We can
also use the isEmpty() method of the Vector class.
• Syntax
• public boolean empty()
• Returns: The method returns true if the stack is empty, else returns
false.
• In the following example, we have created an instance of the Stack
class. After that, we have invoked the empty() method two times.
The first time it returns true because we have not pushed any
element into the stack. After that, we have pushed elements into the
stack. Again we have invoked the empty() method that
returns false because the stack is not empty.
StackEmptyMethodExample.java
import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
Output:
• Is the stack empty? true
• Elements in Stack: [78, 113, 90, 120]
• Is the stack empty? false
Stack Class peek() Method
It looks at the element that is at the top in the stack. It also throws EmptyStackException if the stack is empty.
Syntax
public E peek()
Returns: It returns the top elements of the stack.
Let's see an example of the peek() method.
StackPeekMethodExample.java
import java.util.Stack;
public class StackPeekMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
// pushing elements into Stack
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
stk.push("Orange");
System.out.println("Stack: " + stk);
// Access element from the top of the stack
String fruits = stk.peek();
//prints stack
System.out.println("Element at top: " + fruits);
}
}
Output:
Stack: [Apple, Grapes, Mango, Orange]
Element at the top of the stack: Orange
Stack Class search() Method
• Stack Class search() Method
• The method searches the object in the stack from the top. It
parses a parameter that we want to search for. It returns the
1-based location of the object in the stack. Thes topmost object of
the stack is considered at distance 1.
• Suppose, o is an object in the stack that we want to search for. The
method returns the distance from the top of the stack of the
occurrence nearest the top of the stack. It uses equals() method to
search an object in the stack.
Syntax
• public int search(Object o)
• Parameter: o is the desired object to be searched.
• Returns: It returns the object location from the top of the stack. If
it returns -1, it means that the object is not on the stack.
• Let's see an example of the search() method.


StackSearchMethodExample.java

import java.util.Stack;
public class StackSearchMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
stk.push("Mac Book");
stk.push("HP");
stk.push("DELL");
stk.push("Asus");
System.out.println("Stack: " + stk);
// Search an element
int location = stk.search(“Dell");
System.out.println("Location of Dell: " + location);
}
}
OUTPUT
Queue Interface
• Queue interface maintains the first-in-first-out
order. It can be defined as an ordered list that is
used to hold the elements which are about to be
processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.
• Queue interface can be instantiated as:
• Queue<String> q1 = new PriorityQueue();
• Queue<String> q2 = new ArrayDeque();
• There are various classes that implement the
Queue interface, some of them are given below.
Queue
Method Description

boolean add(object) It is used to insert the specified element into this queue
and return true upon success.

boolean offer(object) It is used to insert the specified element into this queue.

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue,
or returns null if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head 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.
QUEUE EXAMPLE
import java.util.LinkedList; String front = queue.remove();
import java.util.Queue; System.out.println("Removed element: " +
front);
public class QueueExample {
public static void main(String[] args) { // print the updated queue
Queue<String> queue = new System.out.println("Queue after removal:
LinkedList<>(); " + queue);

// add elements to the queue // add another element to the queue


queue.add("apple"); queue.add("date");
queue.add("banana");
queue.add("cherry"); // peek at the element at the front of the
queue
// print the queue String peeked = queue.peek();
System.out.println("Queue: " + queue); System.out.println("Peeked element: " +
peeked);
// remove the element at the front of the
queue // print the updated queue
System.out.println("Queue after peek: " +
queue);
}
}
Output
Queue: [apple, banana, cherry]
Removed element: apple
Queue after removal: [banana, cherry]
Peeked element: banana Queue
after peek: [banana, cherry, date]
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.
• It is already described that the 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.
Priority queue example
// Java program to demonstrate the // Printing the top element of
// creation of queue object using the // the PriorityQueue
// PriorityQueue class System.out.println(pQueue.peek());

import java.util.*; // Printing the top element and


removing it
// from the PriorityQueue container
class GfG {
System.out.println(pQueue.poll());
public static void main(String args[])
// Printing the top element again
{
System.out.println(pQueue.peek());
// Creating empty priority queue
}
Queue<Integer> pQueue= new
PriorityQueue<Integer>(); }

// Adding items to the pQueue


// using add()
pQueue.add(10);
pQueue.add(20);
pQueue.add(15);
• Output
• 10
• 10
• 15
• NOTE: Difference between remove and poll
• The remove() and poll() methods differ only in
their behaviour when the queue is empty: the
remove() method throws an exception, while the
poll() method returns null.
• Difference between add and offer Add is used to
insert a specified element into the queue.
• add() returns true when the task is successful or
else it throws an exception. Offer is used to insert
a specified element into the queue. It returns true
when the task is successful or else its return false
Deque Interface

• Deque interface extends the Queue interface.


In Deque, we can remove and add the elements
from both the side. Deque stands for a
double-ended queue which enables us to
perform the operations at both the ends.
• Deque can be instantiated as:
• Deque d = new ArrayDeque();
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeueDemo {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
// Adding elements from both ends
deque.addFirst("Apple"); // Head
deque.addLast("Banana");
deque.addFirst("Orange");
deque.addLast("Mango");
System.out.println("Deque elements: " + deque);
// Retrieving elements without removal
String first = deque.peekFirst(); // Get head without removing
String last = deque.peekLast(); // Get tail without removing
System.out.println("First element: " + first);
System.out.println("Last element: " + last);
// Removing elements from both ends
String removedFirst = deque.pollFirst(); // Remove and get head
String removedLast = deque.pollLast(); // Remove and get tail
System.out.println("Removed first: " + removedFirst);
System.out.println("Removed last: " + removedLast);
System.out.println("Deque after removals: " + deque);
}
}
OUTPUT
Deque elements: [Orange, Apple, Banana, Mango]
First element: Orange
Last element: Mango
Removed first: Orange
Removed last: Mango
Deque after removals: [Apple, Banana]

You might also like