Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Unit 4

The document provides an overview of the Java Collections Framework, detailing its purpose, key interfaces, and classes such as List, ArrayList, LinkedList, Vector, Stack, and Queue. It explains the functionality of various methods within the Collection and Iterator interfaces, as well as the characteristics of different collection types. Examples of code demonstrate how to create and manipulate collections in Java, highlighting features like element addition, iteration, and removal.

Uploaded by

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

Java Unit 4

The document provides an overview of the Java Collections Framework, detailing its purpose, key interfaces, and classes such as List, ArrayList, LinkedList, Vector, Stack, and Queue. It explains the functionality of various methods within the Collection and Iterator interfaces, as well as the characteristics of different collection types. Examples of code demonstrate how to create and manipulate collections in Java, highlighting features like element addition, iteration, and removal.

Uploaded by

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

Unit 4

Collections
This is the frame work of java. You can call it as API also.
Java collections are the set of pre-defined classes and interfaces that helps programmer to
perform different kinds of data structure operations like sorting searching, traversing, storing
and processing data efficiently.
LIFO - Stack
FIFO - Queue
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection frame work

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

OOPS USING JAVA


Unit 4

Hierarchy of Collection Framework

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

No. Method Description

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

2 public boolean It is used to insert the specified collection


addAll(Collection<? extends elements in the invoking collection.
E> c)

3 public boolean It is used to delete an element from the


remove(Object element) collection.

OOPS USING JAVA


Unit 4

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> c) specified collection from the invoking
collection.

5 default boolean It is used to delete all the elements of the


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

6 public boolean It is used to delete all the elements of invoking


retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the


collection.

8 public void clear() It removes the total number of elements from


the collection.

9 public boolean It is used to search an element.


contains(Object element)

10 public boolean It is used to search the specified collection in the


containsAll(Collection<?> c) collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of the
specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the


parallelStream() collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection


as its source.

17 default Spliterator<E> It generates a Spliterator over the specified


spliterator() elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

OOPS USING JAVA


Unit 4

19 public int hashCode() It returns the hash code number of the


collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean hasNext() It returns true if the iterator has more elements
otherwise it returns false.

2 public Object next() It returns the element and moves the cursor
pointer to the next element.

3 public void remove() It removes the last elements returned by the


iterator. It is less used.

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.
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 subclasses of Collection
interface.

OOPS USING JAVA


Unit 4

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 :
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
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.
import java.util.*;
class A
{
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");

// Traversing list through Iterator


Iterator<String> itr = list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}

OOPS USING JAVA


Unit 4

}
}
Output:
Ravi
Vijay
Ravi
Ajay

=== Code Execution Successful ===


Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including ArrayList and Iterator.
2. Class Definition:
o class A defines the class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating ArrayList:
o ArrayList<String> list=new ArrayList<String>(); creates an ArrayList to store
String objects.
5. Adding Elements:
o list.add("Ravi");, list.add("Vijay");, list.add("Ravi");, and list.add("Ajay"); add
elements to the ArrayList.
6. Creating Iterator:
o Iterator itr=list.iterator(); creates an Iterator for the ArrayList.
7. Traversing the List:
o The while(itr.hasNext()) loop iterates through the ArrayList as long as there are
more elements.
o System.out.println(itr.next()); prints the next element in the iteration.

OOPS USING JAVA


Unit 4

Notes:

 The ArrayList allows duplicate elements, as shown with the two entries of "Ravi".
 The use of an Iterator provides a way to traverse the elements of the ArrayList in the
order they were added.

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.

Consider the following example.

import java.util.*;

public class A

public static void main(String args[])

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

al.add("Ravi"); // Adding elements to LinkedList

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

// Traversing list through Iterator

Iterator<String> itr = al.iterator();

while(itr.hasNext())

System.out.println(itr.next());

OOPS USING JAVA


Unit 4

Output:

Ravi

Vijay

Ravi

Ajay

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including LinkedList and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating LinkedList:
o LinkedList<String> al=new LinkedList<String>(); creates a LinkedList to store
String objects.
5. Adding Elements:
o al.add("Ravi");, al.add("Vijay");, al.add("Ravi");, and al.add("Ajay"); add
elements to the LinkedList.
6. Creating Iterator:
o Iterator<String> itr=al.iterator(); creates an Iterator for the LinkedList.
7. Traversing the List:
o The while(itr.hasNext()) loop iterates through the LinkedList as long as there
are more elements.
o System.out.println(itr.next()); prints the next element in the iteration.

Notes:

The LinkedList allows duplicate elements, as shown with the two entries of "Ravi".

The use of an Iterator provides a way to traverse the elements of the LinkedList in the order
they were added.

OOPS USING JAVA


Unit 4

Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It
is synchronized and contains many methods that are not the part of Collection framework.

Consider the following example.

import java.util.*;

public class A

public static void main(String args[])

Vector<String> v = new Vector<String>(); // Creating Vector

v.add("Ayush"); // Adding elements to Vector

v.add("Amit");

v.add("Ashish");

v.add("Garima");

// Traversing list through Iterator

Iterator<String> itr = v.iterator();

while(itr.hasNext())

System.out.println(itr.next());

Output:

Ayush

OOPS USING JAVA


Unit 4

Amit

Ashish

Garima

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including Vector and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating Vector:
o Vector<String> v = new Vector<String>(); creates a Vector to store String
objects.
5. Adding Elements:
o v.add("Ayush");, v.add("Amit");, v.add("Ashish");, and v.add("Garima"); add
elements to the Vector.
6. Creating Iterator:
o Iterator<String> itr = v.iterator(); creates an Iterator for the Vector.
7. Traversing the Vector:
o The while(itr.hasNext()) loop iterates through the Vector as long as there are
more elements.
o System.out.println(itr.next()); prints the next element in the iteration.

Notes:

The Vector allows duplicate elements and maintains the order of insertion.

The use of an Iterator provides a way to traverse the elements of the Vector in the order they
were added.

Vector is synchronized and thread-safe, unlike ArrayList, but it is generally slower due to this
synchronization.

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

OOPS USING JAVA


Unit 4

import java.util.*;

public class A {

public static void main(String args[]) {

Stack<String> stack = new Stack<String>(); // Creating Stack

stack.push("Ayush"); // Adding elements to Stack

stack.push("Garvit");

stack.push("Amit");

stack.push("Ashish");

stack.push("Garima");

stack.pop(); // Removing the top element ("Garima")

// Traversing stack through Iterator

Iterator<String> itr = stack.iterator();

while(itr.hasNext()) {

System.out.println(itr.next());

Output:

Ayush

Garvit

Amit

Ashish

OOPS USING JAVA


Unit 4

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including Stack and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating Stack:
o Stack<String> stack = new Stack<String>(); creates a Stack to store String
objects.
5. Adding Elements:
o stack.push("Ayush");, stack.push("Garvit");, stack.push("Amit");,
stack.push("Ashish");, and stack.push("Garima"); add elements to the Stack.
6. Removing an Element:
o stack.pop(); removes the top element from the stack (LIFO - Last In First
Out). The element "Garima" will be removed.
7. Creating Iterator:
o Iterator<String> itr = stack.iterator(); creates an Iterator for the Stack.
8. Traversing the Stack:
o The while(itr.hasNext()) loop iterates through the Stack as long as there are
more elements.
o System.out.println(itr.next()); prints the next element in the iteration.

Notes:

The Stack allows duplicate elements and follows the LIFO (Last In First Out) principle.

The pop() method removes the top element from the stack, which in this case is "Garima".

The use of an Iterator provides a way to traverse the elements of the Stack. However, note
that iterating through a Stack in this way will show the elements in the order they were added,
not in the reverse order as might be expected when thinking of stack operations.

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:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

OOPS USING JAVA


Unit 4

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.

Consider the following example.

import java.util.*;

public class A {

public static void main(String args[]) {

PriorityQueue<String> queue = new PriorityQueue<String>(); // Creating PriorityQueue

queue.add("Amit Sharma"); // Adding elements to PriorityQueue

queue.add("Vijay Raj");

queue.add("JaiShankar");

queue.add("Raj");

System.out.println("head: " + queue.element()); // Retrieving head using element()

System.out.println("head: " + queue.peek()); // Retrieving head using peek()

System.out.println("iterating the queue elements:");

Iterator<String> itr = queue.iterator(); // Creating Iterator

while (itr.hasNext()) {

System.out.println(itr.next()); // Printing each element

queue.remove(); // Removing head element

OOPS USING JAVA


Unit 4

queue.poll(); // Removing head element

System.out.println("after removing two elements:");

Iterator<String> itr2 = queue.iterator(); // Creating new Iterator

while (itr2.hasNext()) {

System.out.println(itr2.next()); // Printing each element

Output:

head: Amit Sharma

head: Amit Sharma

iterating the queue elements:

Amit Sharma

Raj

JaiShankar

Vijay Raj

after removing two elements:

Raj

Vijay Raj

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including PriorityQueue and Iterator.
2. Class Definition:

OOPS USING JAVA


Unit 4

o public class A defines the public class named A.


3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating PriorityQueue:
o PriorityQueue<String> queue = new PriorityQueue<String>(); creates a
PriorityQueue to store String objects.
5. Adding Elements:
o queue.add("Amit Sharma");, queue.add("Vijay Raj");,
queue.add("JaiShankar");, and queue.add("Raj"); add elements to the
PriorityQueue.
6. Accessing the Head of the Queue:
o System.out.println("head:" + queue.element()); retrieves and prints the head of
the queue using element(), which throws an exception if the queue is empty.
o System.out.println("head:" + queue.peek()); retrieves and prints the head of
the queue using peek(), which returns null if the queue is empty.
7. Traversing the Queue:
o Iterator itr = queue.iterator(); creates an Iterator for the PriorityQueue.
o The while(itr.hasNext()) loop iterates through the PriorityQueue as long as
there are more elements.
o System.out.println(itr.next()); prints the next element in the iteration.
8. Removing Elements:
o queue.remove(); removes the head of the queue.
o queue.poll(); removes the head of the queue and returns it, or returns null if the
queue is empty.
9. Traversing the Queue After Removals:
o Iterator<String> itr2 = queue.iterator(); creates another Iterator for the
PriorityQueue.
o The while(itr2.hasNext()) loop iterates through the PriorityQueue as long as
there are more elements.
o System.out.println(itr2.next()); prints the next element in the iteration.

Notes:

The PriorityQueue orders elements according to their natural ordering (for strings, it's
lexicographical order) or by a comparator provided at queue construction time.

The element() and peek() methods are used to view the head of the queue. The difference is
that element() throws an exception if the queue is empty, while peek() returns null.

The remove() and poll() methods both remove the head of the queue, but poll() returns null if
the queue is empty, whereas remove() throws an exception.

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:

OOPS USING JAVA


Unit 4

Deque d = new ArrayDeque();

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

import java.util.*;

public class A {

public static void main(String[] args) {

// Creating Deque and adding elements

Deque<String> deque = new ArrayDeque<String>();

deque.add("Gautam");

deque.add("Karan");

deque.add("Ajay");

// Traversing elements

for (String str : deque) {

System.out.println(str);

Output:

Gautam

Karan

Ajay

OOPS USING JAVA


Unit 4

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including Deque and ArrayDeque.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String[] args) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating Deque:
o Deque<String> deque = new ArrayDeque<String>(); creates a Deque using
ArrayDeque to store String objects.
5. Adding Elements:
o deque.add("Gautam");, deque.add("Karan");, and deque.add("Ajay"); add
elements to the Deque.
6. Traversing Elements:
o The enhanced for loop for (String str : deque) iterates through each element in
the Deque.
o System.out.println(str); prints each element in the Deque.

Notes:

The ArrayDeque class provides a resizable array implementation of the Deque interface. It
has no capacity restrictions and can be used as both a queue and a stack.

Elements are added to the end of the deque using the add method.

The enhanced for loop is used to traverse and print each element in the deque in the order
they were added.

ArrayDeque is not thread-safe; if multiple threads access a Deque concurrently and at least
one of the threads modifies the deque, it must be synchronized externally.

Set Interface

Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

OOPS USING JAVA


Unit 4

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.

Consider the following example.

import java.util.*;

public class A {

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"); // Duplicate element

set.add("Ajay");

// Traversing elements

Iterator<String> itr = set.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

Output:

Vijay

Ravi

Ajay

OOPS USING JAVA


Unit 4

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including HashSet and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating HashSet:
o HashSet<String> set = new HashSet<String>(); creates a HashSet to store
String objects.
5. Adding Elements:
o set.add("Ravi");, set.add("Vijay");, set.add("Ravi");, and set.add("Ajay"); add
elements to the HashSet.
o Note: Adding "Ravi" twice demonstrates that HashSet does not allow
duplicate elements.
6. Traversing Elements:
o Iterator<String> itr = set.iterator(); creates an Iterator for the HashSet.
o The while(itr.hasNext()) loop iterates through the HashSet as long as there are
more elements.
o System.out.println(itr.next()); prints each element in the HashSet.

Notes:

The HashSet does not guarantee any specific iteration order of the elements.

Duplicate elements are not added to the HashSet; hence "Ravi" appears only once in the
output.

The use of an Iterator provides a way to traverse the elements of the HashSet.

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements.
It maintains the insertion order and permits null elements.

Consider the following example.

import java.util.*;

OOPS USING JAVA


Unit 4

public class A {

public static void main(String args[]) {

// Creating LinkedHashSet and adding elements

LinkedHashSet<String> set = new LinkedHashSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi"); // Duplicate element

set.add("Ajay");

// Traversing elements

Iterator<String> itr = set.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

Output:

Ravi

Vijay

Ajay

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including LinkedHashSet and Iterator.
2. Class Definition:

OOPS USING JAVA


Unit 4

o public class A defines the public class named A.


3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating LinkedHashSet:
o LinkedHashSet<String> set = new LinkedHashSet<String>(); creates a
LinkedHashSet to store String objects.
5. Adding Elements:
o set.add("Ravi");, set.add("Vijay");, set.add("Ravi");, and set.add("Ajay"); add
elements to the LinkedHashSet.
o Note: Adding "Ravi" twice demonstrates that LinkedHashSet does not allow
duplicate elements.
6. Traversing Elements:
o Iterator<String> itr = set.iterator(); creates an Iterator for the LinkedHashSet.
o The while(itr.hasNext()) loop iterates through the LinkedHashSet as long as
there are more elements.
o System.out.println(itr.next()); prints each element in the LinkedHashSet.

Notes:

 The LinkedHashSet maintains the insertion order of the elements.


 Duplicate elements are not added to the LinkedHashSet; hence "Ravi" appears only once
in the output.
 The use of an Iterator provides a way to traverse the elements of the LinkedHashSet.

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet<data-type> set = new TreeSet();

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.

Consider the following example:

import java.util.*;

public class A {

public static void main(String args[]) {

OOPS USING JAVA


Unit 4

// Creating and adding elements

TreeSet<String> set = new TreeSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi"); // Duplicate element

set.add("Ajay");

// Traversing elements

Iterator<String> itr = set.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

Output:

Ajay

Ravi

Vijay

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including TreeSet and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.

OOPS USING JAVA


Unit 4

4. Creating TreeSet:
o TreeSet<String> set = new TreeSet<String>(); creates a TreeSet to store
String objects.
5. Adding Elements:
o set.add("Ravi");, set.add("Vijay");, set.add("Ravi");, and set.add("Ajay"); add
elements to the TreeSet.
o Note: Adding "Ravi" twice demonstrates that TreeSet does not allow duplicate
elements.
6. Traversing Elements:
o Iterator<String> itr = set.iterator(); creates an Iterator for the TreeSet.
o The while(itr.hasNext()) loop iterates through the TreeSet as long as there are
more elements.
o System.out.println(itr.next()); prints each element in the TreeSet.

Notes:

The TreeSet automatically sorts the elements in their natural order (alphabetical order for
String objects).

Duplicate elements are not added to the TreeSet; hence "Ravi" appears only once in the
output.

The use of an Iterator provides a way to traverse the elements of the TreeSet.

Java Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy


There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given
below:

OOPS USING JAVA


Unit 4

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.

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.

OOPS USING JAVA


Unit 4

Useful methods of Map interface


Method Description

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

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key in
the map only if it is not already specified.

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

boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.

Set keySet() It returns the Set view containing all the keys.

Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and
values.

void clear() It is used to reset the map.

V compute(K key, BiFunction<? super It is used to compute a mapping for the specified key
K,? super V,? extends V> and its current mapped value (or null if there is no
remappingFunction) current mapping).

V computeIfAbsent(K key, Function<? It is used to compute its value using the given mapping
super K,? extends V> function, if the specified key is not already associated
mappingFunction) with a value (or is mapped to null), and enters it into
this map unless null.

V computeIfPresent(K key, It is used to compute a new mapping given the key and
BiFunction<? super K,? super V,? its current mapped value if the value for the specified
extends V> remappingFunction) key is present and non-null.

boolean containsValue(Object value) This method returns true if some value equal to the
value exists within the map, else return false.

OOPS USING JAVA


Unit 4

boolean containsKey(Object key) This method returns true if some key equal to the key
exists within the map, else return false.

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

void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map
super V> action) until all entries have been processed or the action
throws an exception.

V get(Object key) This method returns the object that contains the value
associated with the key.

V getOrDefault(Object key, V It returns the value to which the specified key is


defaultValue) mapped, or defaultValue if the map contains no
mapping for the key.

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, BiFunction<? If the specified key is not already associated with a
super V,? super V,? extends V> value or is associated with null, associates it with the
remappingFunction) given non-null value.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.

void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking
super V,? extends V> function) the given function on that entry until all entries have
been processed or the function throws an exception.

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.

OOPS USING JAVA


Unit 4

Java Map Example: Generic (New Style)

import java.util.*;

class A {

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<Integer, String> m : map.entrySet()) {

System.out.println(m.getKey() + " " + m.getValue());

Output:

100 Amit

101 Vijay

102 Rahul

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including HashMap and Map.
2. Class Definition:

OOPS USING JAVA


Unit 4

o class A defines the class named A.


3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating HashMap:
o Map<Integer,String> map = new HashMap<Integer,String>(); creates a
HashMap to store Integer keys and String values.
5. Adding Elements:
o map.put(100,"Amit");, map.put(101,"Vijay");, and map.put(102,"Rahul"); add
key-value pairs to the HashMap.
6. Traversing Elements:
o for(Map.Entry m : map.entrySet()) iterates through the HashMap entries.
o System.out.println(m.getKey() + " " + m.getValue()); prints the key and value
of each entry.

Notes:

The HashMap does not guarantee any specific order of the elements.

Each key-value pair is added using the put method.

The for loop iterates over the entrySet of the HashMap, which contains all the key-value
pairs.

Java HashMap

Java HashMap class implements the Map interface which allows us to store key and
value pair, where keys should be unique. If you try to insert the duplicate key, it will
replace the element of the corresponding key. It is easy to perform operations using
the key index like updation, deletion, etc. HashMap class is found in
the java.util package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows
us to store the null elements as well, but there should be only one null key. Since Java
5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits
the AbstractMap class and implements the Map interface.

OOPS USING JAVA


Unit 4

Points to remember

o Java HashMap contains values based on the key.


o Java HashMap contains only unique keys.
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

HashMap class Parameters


Let's see the Parameters for java.util.HashMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java HashMap class


Constructor Description

HashMap() It is used to construct a default HashMap.

HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements
extends V> m) of the given Map object m.

HashMap(int capacity) It is used to initializes the capacity of the hash map to the
given integer value, capacity.

HashMap(int capacity, float It is used to initialize both the capacity and load factor of
loadFactor) the hash map by using its arguments.

Methods of Java HashMap class


Method Description

void clear() It is used to remove all of the mappings from this map.

boolean isEmpty() It is used to return true if this map contains no key-value


mappings.

OOPS USING JAVA


Unit 4

Object clone() It is used to return a shallow copy of this HashMap instance:


the keys and values themselves are not cloned.

Set entrySet() It is used to return a collection view of the mappings


contained in this map.

Set keySet() It is used to return a set view of the keys contained in this
map.

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


value)

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V It inserts the specified value with the specified key in the
value) map only if it is not already specified.

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

boolean remove(Object key, It removes the specified values with the associated specified
Object value) keys from the map.

V compute(K key, It is used to compute a mapping for the specified key and
BiFunction<? super K,? its current mapped value (or null if there is no current
super V,? extends V> mapping).
remappingFunction)

V computeIfAbsent(K key, It is used to compute its value using the given mapping
Function<? super K,? function, if the specified key is not already associated with
extends V> a value (or is mapped to null), and enters it into this map
mappingFunction) unless null.

V computeIfPresent(K key, It is used to compute a new mapping given the key and its
BiFunction<? super K,? current mapped value if the value for the specified key is
super V,? extends V> present and non-null.
remappingFunction)

boolean This method returns true if some value equal to the value
containsValue(Object value) exists within the map, else return false.

OOPS USING JAVA


Unit 4

boolean containsKey(Object This method returns true if some key equal to the key exists
key) within the map, else return false.

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

void forEach(BiConsumer<? It performs the given action for each entry in the map until
super K,? super V> action) all entries have been processed or the action throws an
exception.

V get(Object key) This method returns the object that contains the value
associated with the key.

V getOrDefault(Object key, It returns the value to which the specified key is mapped, or
V defaultValue) defaultValue if the map contains no mapping for the key.

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
BiFunction<? super V,? is 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,? extends processed or the function throws an exception.
V> function)

Collection<V> 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.

OOPS USING JAVA


Unit 4

Java HashMap Example


Let's see a simple example of HashMap to store key and value pair.

import java.util.*;

public class A {

public static void main(String args[]) {

// Creating HashMap and adding elements

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

map.put(1, "Mango");

map.put(2, "Apple");

map.put(3, "Banana");

map.put(4, "Grapes");

System.out.println("Iterating HashMap...");

// Traversing elements

for (Map.Entry m : map.entrySet()) {

System.out.println(m.getKey() + " " + m.getValue());

Output:

Iterating HashMap...

1 Mango

2 Apple

3 Banana

OOPS USING JAVA


Unit 4

4 Grapes

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including HashMap and Map.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating HashMap:
o HashMap<Integer, String> map = new HashMap<Integer, String>(); creates a
HashMap to store Integer keys and String values.
5. Adding Elements:
o map.put(1, "Mango");, map.put(2, "Apple");, map.put(3, "Banana");, and
map.put(4, "Grapes"); add key-value pairs to the HashMap.
6. Traversing Elements:
o for (Map.Entry m : map.entrySet()) iterates through the HashMap entries.
o System.out.println(m.getKey() + " " + m.getValue()); prints the key and value
of each entry.

Notes:

The HashMap does not guarantee any specific order of the elements.

Each key-value pair is added using the put method.

The for loop iterates over the entrySet of the HashMap, which contains all the key-value
pairs.

OOPS USING JAVA


Unit 4

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

Points to remember

o Java LinkedHashMap contains values based on the key.


o Java LinkedHashMap contains unique elements.
o Java LinkedHashMap may have one null key and multiple null values.
o Java LinkedHashMap is non synchronized.
o Java LinkedHashMap maintains insertion order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

LinkedHashMap class declaration

Let's see the declaration for java.util.LinkedHashMap class.

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


V>

LinkedHashMap class Parameters

Let's see the Parameters for java.util.LinkedHashMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

OOPS USING JAVA


Unit 4

Constructors of Java LinkedHashMap class

Constructor Description

LinkedHashMap() It is used to construct a default LinkedHashMap.

LinkedHashMap(int It is used to initialize a LinkedHashMap with the given


capacity) capacity.

LinkedHashMap(int capacity, It is used to initialize both the capacity and the load factor.
float loadFactor)

LinkedHashMap(int capacity, It is used to initialize both the capacity and the load factor
float loadFactor, boolean with specified ordering mode.
accessOrder)

LinkedHashMap(Map<? It is used to initialize the LinkedHashMap with the


extends K,? extends V> m) elements from the given Map class m.

Methods of Java LinkedHashMap class

Method Description

V get(Object key) It returns the value to which the specified key is


mapped.

void clear() It removes all the key-value pairs from a map.

boolean containsValue(Object value) It returns true if the map maps one or more keys to
the specified value.

Set<Map.Entry<K,V>> entrySet() It returns a Set view of the mappings contained in


the map.

void forEach(BiConsumer<? super It performs the given action for each entry in the
K,? super V> action) map until all entries have been processed or the
action throws an exception.

V getOrDefault(Object key, V It returns the value to which the specified key is


defaultValue) mapped or defaultValue if this map contains no
mapping for the key.

Set<K> keySet() It returns a Set view of the keys contained in the


map

OOPS USING JAVA


Unit 4

protected boolean It returns true on removing its eldest entry.


removeEldestEntry(Map.Entry<K,V>
eldest)

void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.

Collection<V> values() It returns a Collection view of the values contained


in this map.

Java LinkedHashMap Example

import java.util.*;

class A {

public static void main(String args[]) {

// Creating LinkedHashMap and adding elements

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

hm.put(100, "Amit");

hm.put(101, "Vijay");

hm.put(102, "Rahul");

// Traversing elements

for (Map.Entry<Integer, String> m : hm.entrySet()) {

System.out.println(m.getKey() + " " + m.getValue());

Output:

100 Amit

OOPS USING JAVA


Unit 4

101 Vijay

102 Rahul

=== Code Execution Successful ===

Explanation:

1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including LinkedHashMap and Map.
2. Class Definition:
o class A defines the class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating LinkedHashMap:
o LinkedHashMap<Integer,String> hm = new
LinkedHashMap<Integer,String>(); creates a LinkedHashMap to store Integer
keys and String values.
5. Adding Elements:
o hm.put(100, "Amit");, hm.put(101, "Vijay");, and hm.put(102, "Rahul"); add
key-value pairs to the LinkedHashMap.
6. Traversing Elements:
o for (Map.Entry m : hm.entrySet()) iterates through the LinkedHashMap
entries.
o System.out.println(m.getKey() + " " + m.getValue()); prints the key and value
of each entry.

Notes:

The LinkedHashMap maintains the insertion order of the elements.

Each key-value pair is added using the put method.

The for loop iterates over the entrySet of the LinkedHashMap, which contains all the key-
value pairs.

Java LinkedHashMap Example:remove()

import java.util.*;

public class A {

OOPS USING JAVA


Unit 4

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}

=== Code Execution Successful ===

1. Importing the Package:

import java.util.*;

This imports the Java utility package, which includes the Map and LinkedHashMap classes.

2. Class Definition:

public class A {

Defines a public class named A.

3. Main Method:

OOPS USING JAVA


Unit 4

public static void main(String args[]) {

This is the entry point for the program. The main method is where the program starts
executing.

4. Creating a LinkedHashMap:

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

Creates a LinkedHashMap named map that maps Integer keys to String values.

5. Adding Entries to the Map:

map.put(101, "Amit");

map.put(102, "Vijay");

map.put(103, "Rahul");

Adds three entries to the map with keys 101, 102, and 103 and corresponding values "Amit",
"Vijay", and "Rahul".

6. Printing the Map Before Removal:

System.out.println("Before invoking remove() method: " + map);

Prints the map before removing any entries.

7. Removing an Entry from the Map:

map.remove(102);

Removes the entry with key 102.

8. Printing the Map After Removal:

System.out.println("After invoking remove() method: " + map);

Prints the map after the removal of the entry with key 102.

Java TreeMap class

OOPS USING JAVA


Unit 4

Java TreeMap class is a red-black tree based implementation. It provides an efficient means
of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

o Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.

TreeMap class declaration


Let's see the declaration for java.util.TreeMap class.

public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>,


Cloneable, Serializable

TreeMap class Parameters


Let's see the Parameters for java.util.TreeMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java TreeMap class


Constructor Description

TreeMap() It is used to construct an empty tree map that will be sorted usin
natural order of its key.

OOPS USING JAVA


Unit 4

TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will be sorted u
comparator) the comparator comp.

TreeMap(Map<? extends K,? extends It is used to initialize a treemap with the entries from m, which w
V> m) sorted using the natural order of the keys.

TreeMap(SortedMap<K,? extends V> It is used to initialize a treemap with the entries from the SortedMap
m) which will be sorted in the same order as sm.

Methods of Java TreeMap class


Method Description

Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least key,
greater than or equal to the specified key, or null if
there is no such key.

K ceilingKey(K key) It returns the least key, greater than the specified key
or null if there is no such key.

void clear() It removes all the key-value pairs from a map.

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

Comparator<? super K> It returns the comparator that arranges the key in
comparator() order, or null if the map uses the natural ordering.

NavigableSet<K> It returns a reverse order NavigableSet view of the


descendingKeySet() keys contained in the map.

NavigableMap<K,V> It returns the specified key-value pairs in descending


descendingMap() order.

Map.Entry firstEntry() It returns the key-value pair having the least key.

Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal to the
specified key, or null if there is no such key.

OOPS USING JAVA


Unit 4

void forEach(BiConsumer<? super It performs the given action for each entry in the map
K,? super V> action) until all entries have been processed or the action
throws an exception.

SortedMap<K,V> headMap(K It returns the key-value pairs whose keys are strictly
toKey) less than toKey.

NavigableMap<K,V> headMap(K It returns the key-value pairs whose keys are less than
toKey, boolean inclusive) (or equal to if inclusive is true) toKey.

Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the given
key, or null if there is no such key.

K higherKey(K key) It is used to return true if this map contains a mapping


for the specified key.

Set keySet() It returns the collection of keys exist in the map.

Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key,
or null if there is no such key.

Map.Entry<K,V> lowerEntry(K key) It returns a key-value mapping associated with the


greatest key strictly less than the given key, or null if
there is no such key.

K lowerKey(K key) It returns the greatest key strictly less than the given
key, or null if there is no such key.

NavigableSet<K> It returns a NavigableSet view of the keys contained


navigableKeySet() in this map.

Map.Entry<K,V> pollFirstEntry() It removes and returns a key-value mapping


associated with the least key in this map, or null if the
map is empty.

Map.Entry<K,V> pollLastEntry() It removes and returns a key-value mapping


associated with the greatest key in this map, or null if
the map is empty.

OOPS USING JAVA


Unit 4

V put(K key, V value) It inserts the specified value with the specified key in
the map.

void putAll(Map<? extends K,? It is used to copy all the key-value pair from one map
extends V> map) to another map.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, It replaces the old value with the new value for a
V newValue) specified key.

void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.

NavigableMap<K,V> subMap(K It returns key-value pairs whose keys range from


fromKey, boolean fromInclusive, K fromKey to toKey.
toKey, boolean toInclusive)

SortedMap<K,V> subMap(K It returns key-value pairs whose keys range from


fromKey, K toKey) fromKey, inclusive, to toKey, exclusive.

SortedMap<K,V> tailMap(K It returns key-value pairs whose keys are greater than
fromKey) or equal to fromKey.

NavigableMap<K,V> tailMap(K It returns key-value pairs whose keys are greater than
fromKey, boolean inclusive) (or equal to, if inclusive is true) fromKey.

boolean containsKey(Object key) It returns true if the map contains a mapping for the
specified key.

boolean containsValue(Object It returns true if the map maps one or more keys to
value) the specified value.

K firstKey() It is used to return the first (lowest) key currently in


this sorted map.

OOPS USING JAVA


Unit 4

V get(Object key) It is used to return the value to which the map maps
the specified key.

K lastKey() It is used to return the last (highest) key currently in


the sorted map.

V remove(Object key) It removes the key-value pair of the specified key from
the map.

Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the


map.

int size() It returns the number of key-value pairs exists in the


hashtable.

Collection values() It returns a collection view of the values contained in


the map.

Java TreeMap Example


import java.util.*;

class A {

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<Integer, String> m : map.entrySet()) {

OOPS USING JAVA


Unit 4

System.out.println(m.getKey() + " " + m.getValue());

Output:

100 Amit

101 Vijay

102 Ravi

103 Rahul

=== Code Execution Successful ===

1. Importing the Package:

import java.util.*;

This imports the Java utility package, which includes the Map and TreeMap classes.

2. Class Definition:

class A {

Defines a class named A.

3. Main Method:

public static void main(String args[]) {

This is the entry point for the program. The main method is where the program starts
executing.

4. Creating a TreeMap:

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

Creates a TreeMap named map that maps Integer keys to String values.

5. Adding Entries to the Map:

map.put(100, "Amit");

OOPS USING JAVA


Unit 4

map.put(102, "Ravi");

map.put(101, "Vijay");

map.put(103, "Rahul");

Adds four entries to the map with keys 100, 102, 101, and 103 and corresponding values
"Amit", "Ravi", "Vijay", and "Rahul".

6. Iterating Over the Map Entries:

for (Map.Entry m : map.entrySet()) {

System.out.println(m.getKey() + " " + m.getValue());}

Iterates over the entries of the map using a for-each loop. Each entry is printed with its key
and value.

Java Hashtable class


Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

Points to remember

o 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.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

Hashtable class declaration


Let's see the declaration for java.util.Hashtable class.

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable,


Serializable

Hashtable class Parameters


Let's see the Parameters for java.util.Hashtable class.

OOPS USING JAVA


Unit 4

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java Hashtable class

Constructor Description

Hashtable() It creates an empty hashtable having the initial default


capacity and load factor.

Hashtable(int capacity) It accepts an integer parameter and creates a hash table that
contains a specified initial capacity.

Hashtable(int capacity, It is used to create a hash table having the specified initial
float loadFactor) capacity and loadFactor.

Hashtable(Map<? extends It creates a new hash table with the same mappings as the
K,? extends V> t) given Map.

Methods of Java Hashtable class


Method Description

void clear() It is used to reset the hash table.

Object clone() It returns a shallow copy of the Hashtable.

V compute(K key, BiFunction<? It is used to compute a mapping for the specified key
super K,? super V,? extends V> and its current mapped value (or null if there is no
remappingFunction) current mapping).

V computeIfAbsent(K key, It is used to compute its value using the given mapping
Function<? super K,? extends V> function, if the specified key is not already associated
mappingFunction) with a value (or is mapped to null), and enters it into this
map unless null.

OOPS USING JAVA


Unit 4

V computeIfPresent(K key, It is used to compute a new mapping given the key and
BiFunction<? super K,? super V,? its current mapped value if the value for the specified key
extends V> remappingFunction) is present and non-null.

Enumeration elements() It returns an enumeration of the values in the hash table.

Set<Map.Entry<K,V>> It returns a set view of the mappings contained in the


entrySet() map.

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

void forEach(BiConsumer<? It performs the given action for each entry in the map
super K,? super V> action) until all entries have been processed or the action throws
an exception.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped,
defaultValue) or defaultValue if the map contains no mapping for the
key.

int hashCode() It returns the hash code value for the Map

Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.

Set<K> keySet() It returns a Set view of the keys contained in the map.

V merge(K key, V value, If the specified key is not already associated with a value
BiFunction<? super V,? super V,? or is associated with null, associates it with the given
extends V> remappingFunction) non-null value.

V put(K key, V value) It inserts the specified value with the specified key in the
hash table.

void putAll(Map<? extends K,? It is used to copy all the key-value pair from map to
extends V> t)) hashtable.

V putIfAbsent(K key, V value) If the specified key is not already associated with a value
(or is mapped to null) associates it with the given value
and returns null, else returns the current value.

OOPS USING JAVA


Unit 4

boolean remove(Object key, It removes the specified values with the associated
Object value) specified keys from the hashtable.

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
oldValue, V newValue) specified key.

void replaceAll(BiFunction<? It replaces each entry's value with the result of invoking
super K,? super V,? extends V> the given function on that entry until all entries have
function) been processed or the function throws an exception.

String toString() It returns a string representation of the Hashtable object.

Collection values() It returns a collection view of the values contained in the


map.

boolean contains(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.

boolean containsValue(Object This method returns true if some value equal to the value
value) exists within the hash table, else return false.

boolean containsKey(Object key) This method return true if some key equal to the key
exists within the hash table, else return false.

boolean isEmpty() This method returns true if the hash table is empty;
returns false if it contains at least one key.

protected void rehash() It is used to increase the size of the hash table and
rehashes all of its keys.

V get(Object key) This method returns the object that contains the value
associated with the key.

V remove(Object key) It is used to remove the key and its value. This method
returns the value associated with the key.

OOPS USING JAVA


Unit 4

int size() This method returns the number of entries in the hash
table.

import java.util.*;

class A {

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<Integer, String> m : hm.entrySet()) {

System.out.println(m.getKey() + " " + m.getValue());

Output:

103 Rahul

102 Ravi

101 Vijay

100 Amit

=== Code Execution Successful ===

OOPS USING JAVA


Unit 4

1. Importing the Package:

import java.util.*;

This imports the Java utility package, which includes the Map and Hashtable classes.

2. Class Definition:

class A {

Defines a class named A.

3. Main Method:

public static void main(String args[]) {

This is the entry point for the program. The main method is where the program starts
executing.

4. Creating a Hashtable:

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

Creates a Hashtable named hm that maps Integer keys to String values.

5. Adding Entries to the Hashtable:

hm.put(100, "Amit");

hm.put(102, "Ravi");

hm.put(101, "Vijay");

hm.put(103, "Rahul");

Adds four entries to the hashtable with keys 100, 102, 101, and 103 and corresponding values
"Amit", "Ravi", "Vijay", and "Rahul".

6. Iterating Over the Hashtable Entries:

for (Map.Entry m : hm.entrySet()) {

System.out.println(m.getKey() + " " + m.getValue());

Sorting in Collection
We can sort the elements of:

OOPS USING JAVA


Unit 4

1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of a collection. If collection elements are o
Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides metho
for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List. List elements must be of the
Comparable type.

Example to sort string objects


import java.util.*;

class A {

public static void main(String args[]) {

// Creating an ArrayList to hold String elements

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

// Adding elements to the ArrayList

al.add("Viru");

al.add("Saurav");

al.add("Mukesh");

al.add("Tahir");

// Sorting the ArrayList in alphabetical order

Collections.sort(al);

OOPS USING JAVA


Unit 4

// Creating an iterator to traverse the sorted ArrayList

Iterator<String> itr = al.iterator();

// Iterating through the ArrayList and printing each element

while (itr.hasNext()) {

System.out.println(itr.next());

Output:

Mukesh

Saurav

Tahir

Viru

=== Code Execution Successful ===

Explanation:

1. Imports:

import java.util.*;

This line imports the java.util package, which includes the ArrayList, Collections, and
Iterator classes used in the program.

2. Class Definition:

class A {

This defines a class named A.

3. Main Method:

public static void main(String args[]) {

OOPS USING JAVA


Unit 4

This is the main method, which is the entry point of the program.

4. Creating an ArrayList:

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

This creates an ArrayList to hold String elements.

5. Adding Elements:

al.add("Viru");

al.add("Saurav");

al.add("Mukesh");

al.add("Tahir");

These lines add four names to the ArrayList.

6. Sorting the ArrayList:

Collections.sort(al);

This sorts the elements in the ArrayList in alphabetical order.

7. Creating an Iterator:

Iterator<String> itr = al.iterator();

This creates an iterator for the ArrayList.

8. Iterating and Printing Elements:

while (itr.hasNext()) {

System.out.println(itr.next());

This loop iterates over the ArrayList and prints each element. The hasNext() method checks
if there are more elements, and the next() method returns the next element in the list.

Java 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

OOPS USING JAVA


Unit 4

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

o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.

Java Comparable Example


Let's see the example of the Comparable interface that sorts the list elements on the basis of
age.

import java.util.*;

class Student implements Comparable<Student> {

String name;

int rollNumber;

Student(String name, int rollNumber) {

this.name = name;

this.rollNumber = rollNumber;

// Implement the compareTo method

public int compareTo(Student other) {

return this.rollNumber - other.rollNumber;

OOPS USING JAVA


Unit 4

public String toString() {

return "Student{name='" + name + "', rollNumber=" + rollNumber + "}";

public class Main {

public static void main(String[] args) {

ArrayList<Student> students = new ArrayList<>();

// Adding students to the list

students.add(new Student("Viru", 34));

students.add(new Student("Saurav", 12));

students.add(new Student("Mukesh", 56));

students.add(new Student("Tahir", 23));

// Sorting the list of students

Collections.sort(students);

// Printing the sorted list

for (Student student : students) {

System.out.println(student);

OOPS USING JAVA


Unit 4

Output:

Student{name='Saurav', rollNumber=12}

Student{name='Tahir', rollNumber=23}

Student{name='Viru', rollNumber=34}

Student{name='Mukesh', rollNumber=56}

=== Code Execution Successful ===

Explanation:

1. Student Class:

class Student implements Comparable<Student> {

This declares a Student class that implements the Comparable interface.

2. Fields and Constructor:

String name;

int rollNumber;

Student(String name, int rollNumber) {

this.name = name;

this.rollNumber = rollNumber;

The Student class has two fields, name and rollNumber, and a constructor to initialize these
fields.

3. compareTo Method:

public int compareTo(Student other) {

return this.rollNumber - other.rollNumber;

OOPS USING JAVA


Unit 4

The compareTo method defines the natural ordering of Student objects by rollNumber. If
this.rollNumber is less than other.rollNumber, the method returns a negative value; if they are
equal, it returns zero; and if this.rollNumber is greater, it returns a positive value.

4. toString Method:

public String toString() {

return "Student{name='" + name + "', rollNumber=" + rollNumber + "}";

The toString method provides a string representation of a Student object, which is useful for
printing.

5. Main Class and Method:

public class Main {

public static void main(String[] args) {

ArrayList<Student> students = new ArrayList<>();

The Main class contains the main method, which is the entry point of the program.

6. Adding Students:

students.add(new Student("Viru", 34));

students.add(new Student("Saurav", 12));

students.add(new Student("Mukesh", 56));

students.add(new Student("Tahir", 23));

This adds Student objects to the students list.

7. Sorting the List:

Collections.sort(students);

This sorts the list of Student objects based on the rollNumber field, using the natural ordering
defined by the compareTo method.

8. Printing the Sorted List:

for (Student student : students) {

OOPS USING JAVA


Unit 4

System.out.println(student);

This iterates through the sorted list and prints each Student object.

Java Comparator interface


Java Comparator interface is used to order the objects of a user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object


obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface

Method Description

public int compare(Object obj1, It compares the first object with the second object.
Object obj2)

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

Collections class

Collections class provides static methods for sorting the elements of a collection. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot
sort the elements of List. Collections class provides methods for sorting the elements of List
type elements also.

The Comparator interface in Java is used to define multiple ways of sorting objects that are
different from the natural ordering. It is especially useful when you want to sort objects in
more than one way. Below is an example demonstrating how to use the Comparator interface
to sort a list of custom objects by different fields.

Example:

Suppose we have a class Student with fields name and rollNumber, and we want to sort a list
of Student objects by both name and rollNumber.

OOPS USING JAVA


Unit 4

Student Class:
import java.util.*;

class Student {
String name;
int rollNumber;

Student(String name, int rollNumber) {


this.name = name;
this.rollNumber = rollNumber;
}

public String toString() {


return "Student{name='" + name + "', rollNumber=" + rollNumber + "}";
}
}

Comparators for Sorting:


1. Comparator for Sorting by Name:
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
}
2. Comparator for Sorting by Roll Number:
class RollNumberComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.rollNumber - s2.rollNumber;
}
}

Main Class to Test Comparators:

OOPS USING JAVA


Unit 4

java
Copy code
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();

// Adding students to the list


students.add(new Student("Viru", 34));
students.add(new Student("Saurav", 12));
students.add(new Student("Mukesh", 56));
students.add(new Student("Tahir", 23));

// Sorting by name
System.out.println("Sorting by name:");
Collections.sort(students, new NameComparator());
for (Student student : students) {
System.out.println(student);
}

// Sorting by roll number


System.out.println("\nSorting by roll number:");
Collections.sort(students, new RollNumberComparator());
for (Student student : students) {
System.out.println(student);
}
}
}
Explanation:
1. Student Class:
class Student {

OOPS USING JAVA


Unit 4

String name;
int rollNumber;

Student(String name, int rollNumber) {


this.name = name;
this.rollNumber = rollNumber;
}

public String toString() {


return "Student{name='" + name + "', rollNumber=" + rollNumber + "}";
}
}
This defines a Student class with name and rollNumber fields, a constructor, and a toString
method.
2. NameComparator Class:
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
}
This defines a Comparator that sorts Student objects by name.
3. RollNumberComparator Class:
class RollNumberComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.rollNumber - s2.rollNumber;
}
}
This defines a Comparator that sorts Student objects by rollNumber.
4. Main Class and Method:
public class Main {
public static void main(String[] args) {

OOPS USING JAVA


Unit 4

ArrayList<Student> students = new ArrayList<>();

// Adding students to the list


students.add(new Student("Viru", 34));
students.add(new Student("Saurav", 12));
students.add(new Student("Mukesh", 56));
students.add(new Student("Tahir", 23));

// Sorting by name
System.out.println("Sorting by name:");
Collections.sort(students, new NameComparator());
for (Student student : students) {
System.out.println(student);
}

// Sorting by roll number


System.out.println("\nSorting by roll number:");
Collections.sort(students, new RollNumberComparator());
for (Student student : students) {
System.out.println(student);
}
}
}
o Adding Students: Adds Student objects to the students list.
o Sorting by Name: Uses NameComparator to sort the students list by name and
prints the sorted list.
o Sorting by Roll Number: Uses RollNumberComparator to sort the students list
by rollNumber and prints the sorted list.

Output:
Sorting by name:

OOPS USING JAVA


Unit 4

Student{name='Mukesh', rollNumber=56}
Student{name='Saurav', rollNumber=12}
Student{name='Tahir', rollNumber=23}
Student{name='Viru', rollNumber=34}

Sorting by roll number:


Student{name='Saurav', rollNumber=12}
Student{name='Tahir', rollNumber=23}
Student{name='Viru', rollNumber=34}
Student{name='Mukesh', rollNumber=56}

Difference between comparable interface and comparator


interface
The Comparable and Comparator interfaces in Java are both used to define the ordering of
objects, but they serve different purposes and are used in different contexts. Here are the key
differences between them:
Comparable Interface:
1. Natural Ordering:
o The Comparable interface is used to define the natural ordering of objects.
o A class that implements Comparable must define the compareTo method.
2. Single Sorting Sequence:
o Comparable provides a single sorting sequence, meaning there is only one way
to sort the objects of that class.
3. Implemented by Class:
o The class whose objects need to be ordered must implement the Comparable
interface.
4. compareTo Method:
o Syntax: int compareTo(Object obj)
o It compares the current object with the specified object for order.
5. Modification:
o Modifying the natural order requires changing the class itself.
Comparator Interface:
1. Custom Ordering:

OOPS USING JAVA


Unit 4

o The Comparator interface is used to define multiple ways of sorting objects.


o It can be used to create multiple comparison methods.
2. Multiple Sorting Sequences:
o Comparator can provide multiple sorting sequences, allowing sorting by
different fields or criteria.
3. Implemented by Separate Class:
o Comparator is usually implemented by separate classes, not the class whose
objects need to be ordered.
4. compare Method:
o Syntax: int compare(Object obj1, Object obj2)
o It compares its two arguments for order.
5. Flexibility:
o It allows sorting objects in different ways without modifying the class.

When to Use:

 Use Comparable when there is a natural and consistent way to order objects of a class
and you expect this to be the primary way objects will be compared.
 Use Comparator when you need to define multiple ways to compare objects, or if you
cannot modify the class whose objects need to be compared.

Properties class in Java


The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class
provides methods to get data from the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.

An Advantage of the properties file


Recompilation is not required if the information is changed from a properties
file: If any information is changed from the properties file, you don't need to recompile
the java class. It is used to store information which is to be changed frequently.

Constructors of Properties class


Method Description

OOPS USING JAVA


Unit 4

Properties() It creates an empty property list with no default values.

Properties(Properties defaults) It creates an empty property list with the specified


defaults.

Methods of Properties class


The commonly used methods of Properties class are given below.

Method Description

public void load(Reader r) It loads data from the Reader object.

public void It loads data from the InputStream object


load(InputStream is)

public void It is used to load all of the properties represented by


loadFromXML(InputStream the XML document on the specified input stream into
in) this properties table.

public String It returns value based on the key.


getProperty(String key)

public String It searches for the property with the specified key.
getProperty(String key,
String defaultValue)

public void It calls the put method of Hashtable.


setProperty(String key,
String value)

public void list(PrintStream It is used to print the property list out to the specified
out) output stream.

public void list(PrintWriter It is used to print the property list out to the specified
out)) output stream.

public Enumeration<?> It returns an enumeration of all the keys from the


propertyNames()) property list.

public Set<String> It returns a set of keys in from property list where the
stringPropertyNames() key and its corresponding value are strings.

OOPS USING JAVA


Unit 4

public void store(Writer w, It writes the properties in the writer object.


String comment)

public void It writes the properties in the OutputStream object.


store(OutputStream os,
String comment)

public void It writes the properties in the writer object for


storeToXML(OutputStream generating XML document.
os, String comment)

public void It writes the properties in the writer object for


storeToXML(Writer w, String generating XML document with the specified
comment, String encoding) encoding.

Example of Properties class to get information from the


properties file
import java.util.*;

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:

OOPS USING JAVA


Unit 4

awt.toolkit = sun.awt.X11.XToolkit

java.specification.version = 11

sun.cpu.isalist =

sun.jnu.encoding = ANSI_X3.4-1968

java.class.path = /tmp/qjXCZTi3ew

java.vm.vendor = SAP SE

sun.arch.data.model = 64

java.vendor.url = https://sapmachine.io/

user.timezone =

os.name = Linux

java.vm.specification.version = 11

sun.java.launcher = SUN_STANDARD

user.country = US

sun.boot.library.path = /usr/lib/jvm/sapmachine-11/lib

sun.java.command = Test

jdk.debug = release

sun.cpu.endian = little

user.home = /home/compiler

user.language = en

java.specification.vendor = Oracle Corporation

java.version.date = 2024-01-16

java.home = /usr/lib/jvm/sapmachine-11

file.separator = /

java.vm.compressedOopsMode = 32-bit

line.separator =

OOPS USING JAVA


Unit 4

java.specification.name = Java Platform API Specification

java.vm.specification.vendor = Oracle Corporation

java.awt.graphicsenv = sun.awt.X11GraphicsEnvironment

sun.management.compiler = HotSpot 64-Bit Tiered Compilers

java.runtime.version = 11.0.22+7-LTS-sapmachine

user.name = compiler

path.separator = :

os.version = 6.1.75+

java.runtime.name = OpenJDK Runtime Environment

file.encoding = ANSI_X3.4-1968

java.vm.name = OpenJDK 64-Bit Server VM

java.vendor.version = SapMachine

java.vendor.url.bug = https://github.com/SAP/SapMachine/issues/new

java.io.tmpdir = /tmp

java.version = 11.0.22

user.dir = /home/compiler

os.arch = amd64

java.vm.specification.name = Java Virtual Machine Specification

java.awt.printerjob = sun.print.PSPrinterJob

sun.os.patch.level = unknown

java.library.path = /usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib

java.vm.info = mixed mode

java.vendor = SAP SE

java.vm.version = 11.0.22+7-LTS-sapmachine

OOPS USING JAVA


Unit 4

java.specification.maintenance.version = 2

sun.io.unicode.encoding = UnicodeLittle

java.class.version = 55.0

=== Code Execution Successful ===

Explanation of the Code:

1. Imports:

import java.util.*;

import java.io.*;

These lines import the necessary classes from the java.util and java.io packages. In this
specific code snippet, the java.io.* import is not required as file handling is not used.

2. Class Definition:

public class Test {

This defines a public class named Test.

3. Main Method:

public static void main(String[] args) throws Exception {

The main method is the entry point of the program and it throws a generic Exception to
handle any errors that may occur.

4. Getting System Properties:

Properties p = System.getProperties();

This retrieves all system properties and stores them in a Properties object.

5. Creating a Set of Entries:

Set set = p.entrySet();

OOPS USING JAVA


Unit 4

This converts the properties object into a set of key-value pairs.

6. Iterator for Traversing the Set:

Iterator itr = set.iterator();

This creates an iterator to traverse the set of properties.

7. Iterating and Printing Properties:

while (itr.hasNext()) {

Map.Entry entry = (Map.Entry) itr.next();

System.out.println(entry.getKey() + " = " + entry.getValue()); }

OOPS USING JAVA

You might also like