0% found this document useful (0 votes)
10 views88 pages

Unit 4

Report

Uploaded by

robingurung3333
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)
10 views88 pages

Unit 4

Report

Uploaded by

robingurung3333
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/ 88

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000
Department: Computer Science and Engineering

Unit-4
What is Collection in Java
A collection is a group of objects. In Java, these objects are called elements of the collection.
For Example:
1. A classroom is a collection of students. So, the classroom is nothing but a collection and students are
objects.
2. We know that the entire world is a collection of humans, animals, and different things. The world is a
collection and humans, animals and different things are different objects.
Technically, a collection is an object or container which stores a group of other objects as a single unit or
single entity. Therefore, it is also known as container object or collection object in java.
A container object means it contains other objects. In simple words, a collection is a container that stores
multiple elements together.
JVM (Java Virtual Machine) stores the reference of other objects into a collection object. It never stores
physical copies of other objects because other objects are already available in the memory and storing another
copy of objects into a collection object would be a wasting of memory.

A collection object has a class that is known as collection class or container class. All collection classes are
present in java.util package.
A collection object has a class that is known as collection class or container class. All collection classes are
present in java.util package.
A simple example of a collection is:
// Create a container list of cities (objects or elements).
List<String> city = new ArrayList<String>();
1
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Adding names of cities.


city.add(“New York”);
city.add(“Dhanbad”);
city.add(“Mumbai”);

Types of Objects Stored in Collection (Container) Object

There are two types of objects that can be stored in a collection or container object. They are as follows:
1. Homogeneous objects:
Homo means same. Homogeneous objects are a group of multiple objects that belong to the same class.
For example, suppose we have created three objects Student s1, Student s2, and Student s3 of the same class
‘Student’. Since these three objects belong to the same class that’s why they are called homogeneous objects.
2. Heterogeneous objects:
Hetero means different. Heterogeneous objects are a group of different objects that belong to different classes.
For example, suppose we have created two different objects of different classes such as one object Student s1,
and another one object Employee e1. Here, student and employee objects together are called a collection of
heterogeneous objects.

These objects can also be further divided into two types. They are as follows:
1. Duplicate objects:
The multiple objects of a class that contains the same data are called duplicate objects. For example, suppose
we create two person objects Person p1 and Person p2. Both of these objects have the same data.
Person p1 = new Person( "abc");
Person p2 = new Person("abc");
2. Unique objects:
Since the above two objects have the same data “abc” therefore, these are called duplicate objects.
The multiple objects of a class that contains different data are called unique objects. For example:
Person p1 = new Person("abcd");
Person p2 = new Person("abcde");
A unique or duplicate object depends on its internal data.
2
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

What is need for Collections in Java?


Actually, there is a total of four ways to store values in Java application by JVM.
1. Using variable approach:
2. Using class object approach:
3. Using array object approach:
4. Using collection object:

1. Using variable approach:

For storing one value we need to create one variable and assign a value0, like this: int x = 10;
The purpose of variable x is to store one int value 10. If we want to store two int values, we will create
two variables like this:
int x = 10;
int y = 20;
Similarly, for three values, the third variable will be required, and so on.
There is no problem to store until the third or fourth value. But if we want to store 5000 values then
declaring 5000 variables in a program is the worst kind of programming practice.

Thus, the limitations of using the variable approach are as follows:


• The limitation of a variable is that it can store only one value at a time.
• The readability and reusability of the code will be down.
• JVM will take more time for execution.

2. Using class object approach:

Using a class object, we can store multiple “fixed” number of values of different types. For example,
suppose we have created a class named Employee and declare two variables inside the class.

class Employee
{
int eNo;
String eName;
}

// Creating an object of Employee class.


Employee e1 = new Employee();

This employee object can store only two values but if we will want to store the third value, it will not
possible. Therefore, this approach is only suitable to store a fixed number of different values.
3
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

To overcome this problem, we should use the third technique “Array object”.

3. Using array object approach:

We can store a group of objects into an array. Suppose we want to store 5000 objects of Student class into
an array.
For this purpose, we need to create an array object of Student type like this:
Student[ ] st = new Student[5000];

This array can store 5000 Student objects.

The biggest advantage of an array is that we can store a huge number of values by using a single variable
st and retrieve them easily.
Array mechanism helps to improve the readability of the code in java programming but there are several
types of problems and limitations with the array. They are as follows:

1. We can easily store multiple “fixed” numbers of values of homogeneous data type i.e. an array can store
only similar types of data. Suppose if we create an Employee type array object like this:
Employee[ ] emp = new Employee[5000]; // It will hold only employee type objects.

For example:
emp[0] = new Employee(); // valid.
emp[1] = new Customer(); // invalid because here, we are providing the customer type object.

We can resolve this problem by using an object array.


Object[ ] ob = new Object[5000];
ob[0] = new Employee(); // valid.
ob[1] = new Customer(); // valid.
From the above code, it is clear that we cannot store different class objects into the same array. This is because
an array can store only one data type of elements (objects).
4
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

2. An array is static in nature. It is fixed in length and size. We cannot change (increase/decrease) the size of
the array based on our requirements once they created.
3. We can add elements at the end of an array easily. But, adding and deleting elements or objects in the
middle of array is difficult.
4. We cannot insert elements in some sorting order using array concept because array does not support any
method. We will have to write the sorting code for this but in the case of collection, ready-made method
support is available for sorting using Tree set.
5. We cannot search a particular element using an array, whether the particular element is present or not in
the array index. For this, we will have to write the searching code using array but in the case of collection,
one readymade method called contains() method is available.
Due to all these above limitations of array, programmers need a better mechanism to store a group of objects.
So, the alternative option is a collection object or container object in java.
4. Using collection object:

By using collection object, we can store the same or different data without any size limitation. Thus,
technically, we can define the collections as:
A collection in Java is a container object that is used for storing multiple homogeneous and heterogeneous,
duplicate, and unique elements without any size limitation.

Framework in java
Java frameworks are the prewritten code used by developers to create applications in the java language.

What is Collections Framework in Java?


A framework in java is a set of several classes and interfaces which provide a ready-made architecture.
A Java collections framework is a hierarchy of several predefined interfaces and implementation classes that
can be used to handle a group of objects as a single entity.
In other words, a collections framework is a class library to handle groups of objects. It is present in java.util
package. It allows us to store, retrieve, and update a group of objects.
Collections framework in Java supports two types of containers:
▪ One for storing a collection of elements (objects), that is simply called a collection.
▪ The other, for storing key/value pairs, which is called a map.
Java collections framework provides an API to work with data structures such as lists, trees, sets, and maps.
It offers a set of reusable data structures, algorithms, and utilities for managing collections of objects in Java
programming.

5
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

It saves developers time and effort by providing efficient implementations of common data structures. In
multi-threaded environments, working with collections can be challenging because of the possibility of race
conditions and other concurrency issues.

Why the Collections Framework?


The Java collections framework provides various data structures and algorithms that can be used directly. This
has two main advantages:
• We do not have to write code to implement these data structures and algorithms manually.
• Our code will be much more efficient as the collections framework is highly optimized.
Moreover, the collections framework allows us to use a specific data structure for a particular type of data.
Here are a few examples,
• If we want our data to be unique, then we can use the Set interface provided by the collections
framework.
• To store data in key/value pairs, we can use the Map interface.
• The ArrayList class provides the functionality of resizable arrays.

Key Interfaces in Collections Framework


Java programming language built the collections framework around the following core interfaces:
• Collection
• List
• Set
• Queue
• Map
• Iterator

6
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

→The Map interface is also part of the java collection framework but it does not inherit the collection interface.
The map interface is preferred when values are stored in the form of keys and value pairs.
Map Interface implemented using following classes:-
• Hashmap
• LinkedHashmap
• HashTable
These interfaces provide different ways of managing groups of objects, depending on the requirements.
1. List Interface
The List interface is an ordered collection that allows us to add and remove elements like an array.
2. Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have
duplicate elements.
3. Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner.
4. Java Map Interface
In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique names that can be
used to access a particular element in a map. And, each key has a single value associated with it.
7
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

5. Java Iterator Interface


In Java, the Iterator interface provides methods that can be used to access elements of collections.

List of Interfaces defined in java.util package


Collection List Queue
Comparator ListIterator RandomAccess
Deque Map Set
Enumeration Map.Entry SortedMap
EventListener NavigableMap SortedSet
Formattable NavigableSet
Iterator Observer

Some of the most commonly used implementations of the Collections Framework in Java are as:
• ArrayList
• LinkedList
• HashSet
• HashMap
• TreeMap
• TreeSet

Difference between Arrays & Collections in Java


The difference between arrays and collections are as follows:
1. Arrays are fixed in size but collections are growable in nature. We can increase or decrease size.
2. Arrays can store only homogeneous data elements (similar type of data) but collections can hold both
homogeneous and heterogeneous elements.
3. Arrays do not support any method but collections support various kinds of methods.
4. Arrays can have both hold primitives and object types but collections can hold only objects but not
primitive.

8
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Advantage of Collections Framework in Java

The advantages of the collections framework in java are as follows:


1. The collections framework reduces the development time and the burden of designers, programmers,
and users.
2. Code is easier to maintain because it provides useful data structure and interfaces which reduce
programming efforts.
3. The size of the container is growable in nature.
4. It implements high-performance of useful data structures and algorithms that increase the performance.
5. It enables software reuse.

Limitation of Collections Framework in Java


There are two limitations of the collection’s framework in Java. They are as follows:
1. Care must be taken to use the appropriate cast operation.
2. Compile type checking is not possible.

Hierarchy of Collection Framework

The hierarchy of the entire collection framework consists of four core interfaces such as Collection, List, Set,
Map, and two specialized interfaces named SortedSet and SortedMap for sorting.
All the interfaces and classes for the collection framework are located in java.util package.

9
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

e➝ extends, I➝ implements
Extends: Extends is a keyword that is used for developing inheritance between two classes and two interfaces.
Implements: Implements is a keyword used for developing inheritance between class and interface

Collection Interface in Java

1. The basic interface of the collections framework is the Collection interface which is the root interface of
all collections in the API (Application Programming Interface).

It is placed at the top of the collection hierarchy in java. It provides the basic operations for adding and
removing elements in the collection.

2. Collection interface extends the Iterable interface. The iterable interface has only one method called
iterator(). The function of the iterator method is to return the iterator object. Using this iterator object, we
can iterate over the elements of the collection.

10
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

3. List, Queue, and Set have three components which extends the Collection interface. A map is not inherited
by Collection interface.

Java Collection Interface


The Collection interface is the root interface of the collections framework hierarchy.
Java does not provide direct implementations of the Collection interface but provides implementations of its
subinterfaces like List, Set, and Queue.

For example, the ArrayList class implements the List interface which is a subinterface of
the Collection Interface.

Collections Framework Vs. Collection Interface


The Collection interface is the root interface of the collections framework. The framework includes other
interfaces as well: Map and Iterator. These interfaces may also have subinterfaces.

Methods present in the collection interface

Sr.no Method Description

1 add(Object o) To insert an element in the collection.

11
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

2 addAll(Collection c) To insert another collection in the present collection.

3 remove(Object o) To remove an element in the collection.

removeAll(Collection To remove another collection from the present collection if another


4
c) is inserted.

To remove all the collection elements that are not contained in the
5 retain(collection c)
specified collection.

6 clear() It removes all the elements from the collection.

7 isEmpty() It checks collection is empty or not and provides true or false.

It gives the total number of elements present in the collection in


8 size()
form of a numeric value.

9 equals(collection c) It is used to check if the two collections are the same or not.

10 toArray(collection c) It converts collection into an array.

It is used for searching. If an element is present in the collection it


11 contains(Object o)
returns true or false.

It is used for searching. If elements of another collection are present


12 contains(collection c)
in the collection or not. If present returns true or false.

Subinterfaces of the Collection Interface


Collection interface includes subinterfaces that are implemented by Java classes.All the methods of
the Collection interface are also present in its subinterfaces.
List Interface
The List interface is an ordered collection that allows us to add and remove elements like an array.
Set Interface
12
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have
duplicate elements.
Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner.

Java Iterator Interface

The Iterator interface of the Java collections framework allows us to access elements of a collection. It has a
subinterface ListIterator.

All the Java collections include an iterator() method. This method returns an instance of iterator used to
iterate over elements of collections.

13
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Methods of Iterator
The Iterator interface provides 4 methods that can be used to perform various operations on elements of
collections.
• hasNext() - returns true if there exists an element in the collection
• next() - returns the next element of the collection
• remove() - removes the last element returned by the next()
• forEachRemaining() - performs the specified action for each remaining element of the collection

import java.util.ArrayList;
import java.util.Iterator;

public class collframe1


{
public static void main(String[] args)
{
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
System.out.println("ArrayList: " + numbers);

// Creating an instance of Iterator


Iterator<Integer> iterate = numbers.iterator();

// Using the next() method


int number = iterate.next();
System.out.println("Accessed Element: " + number);

// Using the remove() method


iterate.remove();
System.out.println("Removed Element: " + number);

System.out.print("Updated ArrayList: ");

// Using the hasNext() method


while(iterate.hasNext())
{
// Using the forEachRemaining() method
iterate.forEachRemaining((value) -> System.out.print(value + ", "));
}

14
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}

Java ListIterator Interface


The ListIterator interface of the Java collections framework provides the functionality to access elements of
a list.
It is bidirectional. This means it allows us to iterate elements of a list in both the direction.It extends
the Iterator interface.

The List interface provides a listIterator() method that returns an instance of the ListIterator interface.

Methods of ListIterator
The ListIterator interface provides methods that can be used to perform various operations on the elements of
a list.
• hasNext() - returns true if there exists an element in the list
• next() - returns the next element of the list
• nextIndex() returns the index of the element that the next() method will return
• previous() - returns the previous element of the list
• previousIndex() - returns the index of the element that the previous() method will return

15
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

• remove() - removes the element returned by either next() or previous()


• set() - replaces the element returned by either next() or previous() with the specified element

import java.util.ArrayList;
import java.util.ListIterator;

class collframe2 {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(7);
numbers.add(9);
numbers.add(5);
System.out.println("ArrayList: " + numbers);

// Creating an instance of ListIterator


ListIterator<Integer> iterate = numbers.listIterator();

int index = iterate.nextIndex();


System.out.println("Position of Next Element: " + index);

// Using the next() method


int number1 = iterate.next();
System.out.println("Next Element: " + number1);

// Using the nextIndex()


int index1 = iterate.nextIndex();
System.out.println("Index of Next Element: " + index1);

// Using the hasNext() method


System.out.println("Is there any next element? " + iterate.hasNext());
}
}

16
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

List interface
List is the child interface of Collection interface. If we want to represent a group of individual objects as single
entity where duplicates are allowed and insertion order must be preserved, They appear in the same order in
which we inserted.
List Interface is implemented by using :
• ArrayList
• LinkedList
• Vector
• Stack

These classes are defined in the Collections framework and implement the List interface.

ArrayList

• ArrayList is a class present in java. util package.


• It provides a dynamic array for storing the element.
• It is an array but there is no size limit.
• We can add or remove elements easily.
• It is more flexible than a traditional array.

Creation of Array List:

ArrayList<DataType> VariableName=new ArrayList<DataTYpe>();

Methods in ArrayList:

Sr.no Method Description

1 get(object o) It prints the value at a specific index.

17
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

2 set(index, object o) It updates the value. In that, we need to provide an index.

3 add(index, object o) It adds an element at a specific index.

4 remove(Object o) It removes elements at specific indexes.

5 sort() It sorts an array depending upon the data type.

6 addAll(Collection c) It is used to add another collection.

7 removeAll(Collection c) It is used to remove another collection.

Example1:
import java.util.List;
import java.util.ArrayList;
class arryl1 {
public static void main(String[] args) {
// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();

// Add elements to the list


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);

// Access element from the list


int number = numbers.get(2);
System.out.println("Accessed Element: " + number);

// Remove element from the list


int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}

18
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

LinkedList
Linked List is a part of the Collection framework present in java.util package. This class is an implementation
of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous
locations and every element is a separate object with a data part and address part. The elements are linked
using pointers and addresses. Each element is known as a node.
• LinkedList class uses a doubly LinkedList to store element. i.e., the user can add data at the first
position as well as the last position.
• The dequeue interface is implemented using the LinkedList class.
• Null insertion is possible.
• If we need to perform insertion /Deletion operation the LinkedList is preferred.
• LinkedList is used to implement Stacks and Queues.

Creation of a LinkedList
LinkedList<DataType> VariableName = new LinkedList < DataType>();

Methods in LinkedList Interface:


Some methods in LinkedList are the same as ArrayList
Other methods in LinkedList are:
• addFirst()
• addLast()
• removeFirst()
• removeLast()
• getFirst()
• getLast()

19
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Example1:
20
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

import java.util.LinkedList;

class Linklist1 {
public static void main(String[] args){

// create linkedlist
LinkedList<String> pl = new LinkedList<>();

// Add elements to LinkedList


pl.add("C");
pl.add("C++");
pl.add("Java");
System.out.println("LinkedList: " + pl);
}
}

Example:2
import java.util.List;
import java.util.LinkedList;

class linklist {

public static void main(String[] args) {


// Creating list using the LinkedList class
List<Integer> numbers = new LinkedList<>();

// Add elements to the list


numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println("List: " + numbers);

// Access element from the list


int number = numbers.get(2);
System.out.println("Accessed Element: " + number);

21
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Using the indexOf() method


int index = numbers.indexOf(2);
System.out.println("Position of 30 is " + index);

// Remove element from the list


int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}

Example-3

import java.util.*;
public class Linklist2
{
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("C");
list.add("C++");
list.add("Python");
list.add("Java");
list.add("PHP");
System.out.println("Original list is: "+ list);
list.addFirst("scala");
list.addFirst("HTML");
System.out.println("After adding element by using addFirst() method: " + list);
list.removeFirst();
System.out.println("After adding element by using removeFirst() method: " + list);
System.out.println("After adding element by using getFirst() method: " + list.getFirst());
list.addLast("CSS");
System.out.println("After adding element by using addLast() method: " + list);
list.removeLast();
System.out.println("After adding element by using removeLast() method: " + list);
System.out.println("After adding element by using getLast() method: " + list.getLast());
}
}

22
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Java Vector

The Vector class is an implementation of the List interface that allows us to create resizable-arrays similar to
the ArrayList class.

Java Vector vs. ArrayList

In Java, both ArrayList and Vector implements the List interface and provides the same functionalities.
However, there exist some differences between them.

The Vector class synchronizes each individual operation. This means whenever we want to perform some
operation on vectors, the Vector class automatically applies a lock to that operation.

It is because when one thread is accessing a vector, and at the same time another thread tries to access it, an
exception called ConcurrentModificationException is generated. Hence, this continuous use of lock for each
operation makes vectors less efficient.

However,in array lists, methods are not synchronized. Instead, it uses


the Collections.synchronizedList() method that synchronizes the list as a whole.

Creation of Vector:
Vector < DataType> VariableName = new Vector<DataType> ();

23
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Methods in Vector Class:

import java.util.Iterator;
import java.util.Vector;

class Vectorlist {
public static void main(String[] args) {
Vector<String> pl= new Vector<>();

24
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Using the add() method


pl.add("Java");
pl.add("Python");

// Using index number


pl.add(2, "Cotlon");
System.out.println("Vector: " + pl);

// Using addAll()
Vector<String> course = new Vector<>();
course.add("B.Tech");
System.out.println("New Vector: " + course);
course.addAll(pl);
System.out.println("Now Vector is: " + course);

//Access Vector Elements

String element = course.get(2);


System.out.println("Element at index 2: " + element);

// Using iterator()
Iterator<String> iterate = course.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}

//Remove Vector Elements

// Using remove()
String ele = course.remove(1);
System.out.println("Removed Element: " + ele);
System.out.println("New Vector: " + course);

// Using clear()
course.clear();
System.out.println("Vector after clear(): " + course);

}
}

25
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Java Stack Class

The Java collections framework has a class named Stack that provides the functionality of the stack data
structure.
The Stack class extends the Vector class.

Stack Implementation
In stack, elements are stored and accessed in Last In First Out manner. That is, elements are added to the
top of the stack and removed from the top of the stack.

26
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Creating a Stack:

In order to create a stack, we must import the java.util.Stack package first. Once we import the package,
here is how we can create a stack in Java.

Stack<Type> stacks = new Stack<>();

Methods in Stack Class

Method Description

empty() It returns true if nothing is on the top of the stack. Else, returns false.

peek() Returns the element on the top of the stack, but does not remove it.

Removes and returns the top element of the stack. An ‘EmptyStackException’


pop()
An exception is thrown if we call pop() when the invoking stack is empty.

push(Object element) Pushes an element on the top of the stack.

It determines whether an object exists in the stack. If the element is found,


search(Object
It returns the position of the element from the top of the stack. Else, it returns -
element)
1.

import java.util.Stack;

27
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public class Stackcoll {

public static void main(String[] args) {


// Creating a Stack
Stack<Integer> stack = new Stack<>();

// Pushing elements into the Stack


stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);

// Display the Stack


System.out.println("Stack: " + stack);

// Popping an element from the Stack


int poppedElement = stack.pop();
System.out.println("Popped Element: " + poppedElement);

// Display the Stack after pop


System.out.println("Stack after pop: " + stack);

// Peeking the top element of the Stack


int topElement = stack.peek();
System.out.println("Top Element: " + topElement);

// Checking if the Stack is empty


boolean isEmpty = stack.isEmpty();
System.out.println("Is the stack empty? " + isEmpty);

// Searching for an element in the Stack


int searchElement = 20;
int position = stack.search(searchElement);
if (position != -1) {
System.out.println("Element " + searchElement + " found at position: " + position);
} else {
System.out.println("Element " + searchElement + " not found in the stack.");
}

// Getting the size of the Stack


int size = stack.size();
System.out.println("Size of the stack: " + size);
28
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}

Queue Interface
The Queue interface of the Java collections framework provides the functionality of the queue data structure.
It extends the Collection interface. It is used to store elements that are going to be processed in First In First
Out (FIFO) order.
It adheres to the First-In-First-Out, or FIFO, concept, queue is an ordered collection of the homogeneous
group of elements in which new elements are added at one end(rear) and elements are removed from the other
end(front).

Classes that Implement Queue:


Since the Queue is an interface, we cannot provide the direct implementation of it.
In order to use the functionalities of Queue, we need to use classes that implement it:
• ArrayDeque
• LinkedList
• PriorityQueue

29
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Interfaces that extend Queue


The Queue interface is also extended by various subinterfaces:
• Deque
• BlockingQueue
• BlockingDeque

Creating Queue Objects:

Queue can be defined as:


Queue<Obj> queue = new PriorityQueue<Obj> ();

30
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Methods of Queue

The Queue interface includes all the methods of the Collection interface. It is because Collection is the super
interface of Queue.
Some of the commonly used methods of the Queue interface are:
• add() - Inserts the specified element into the queue. If the task is successful, add() returns true, if not
it throws an exception.
• offer() - Inserts the specified element into the queue. If the task is successful, offer() returns true, if
not it returns false.
• element() - Returns the head of the queue. Throws an exception if the queue is empty.
• peek() - Returns the head of the queue. Returns null if the queue is empty.
• remove() - Returns and removes the head of the queue. Throws an exception if the queue is empty.
• poll() - Returns and removes the head of the queue. Returns null if the queue is empty.

Implementation of the Queue Interface:


1. Implementing the LinkedList Class:
import java.util.Queue;
import java.util.LinkedList;

class Queueimp1 {

public static void main(String[] args) {


// Creating Queue using the LinkedList class
Queue<Integer> numbers = new LinkedList<>();

// offer elements to the Queue


numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

31
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("Updated Queue: " + numbers);


}
}

2. Implementing the PriorityQueue Class:


import java.util.Queue;
import java.util.PriorityQueue;

class Queueimp2 {

public static void main(String[] args) {


// Creating Queue using the PriorityQueue class
Queue<Integer> numbers = new PriorityQueue<>();

// offer elements to the Queue


numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
System.out.println("Queue: " + numbers);

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);


}
}

32
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Set Interface

The set interface is present in java.util package and extends the Collection interface. It is an unordered
collection of objects in which duplicate values cannot be stored. It is an interface that implements the
mathematical set. This interface contains the methods inherited from the Collection interface and adds a
feature that restricts the insertion of the duplicate elements.
There are two interfaces that extend the set implementation namely SortedSet and NavigableSet.
Characteristics Of A Set:
1. No Duplicates:
2. Unordered Collection
3. Single Null Value:
Classes that implement Set

Since Set is an interface, we cannot create objects from it.


In order to use functionalities of the Set interface, we can use these classes:
• HashSet
• LinkedHashSet
• EnumSet
• TreeSet
These classes are defined in the Collections framework and implement the Set interface.

33
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Interfaces that extend Set

The Set interface is also extended by these subinterfaces:


• SortedSet
• NavigableSet

Creation of Set:
In Java, we must import java.util.Set package in order to use Set.
// Set implementation using HashSet
Set<String> Subject = new HashSet<>();

Methods of Set

The Set interface includes all the methods of the Collection interface. It's because Collection is a super
interface of Set.
34
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Some of the commonly used methods of the Collection interface that's also available in the Set interface are:
• add() - adds the specified element to the set
• addAll() - adds all the elements of the specified collection to the set
• iterator() - returns an iterator that can be used to access elements of the set sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another specified set
• retainAll() - retains all the elements in the set that are also present in another specified set
• clear() - removes all the elements from the set
• size() - returns the length (number of elements) of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element
• containsAll() - returns true if the set contains all the elements of the specified collection
• hashCode() - returns a hash code value (address of the element in the set)

Set Operations

The Java Set interface allows us to perform basic mathematical set operations like union, intersection, and
subset.
• Union - to get the union of two sets x and y, we can use x.addAll(y)
• Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
• Subset - to check if x is a subset of y, we can use y.containsAll(x)

Implementation of the Set Interface

1. Implementing HashSet Class:

import java.util.Set;
import java.util.HashSet;

class Setimp1 {

public static void main(String[] args) {


// Creating a set using the HashSet class
35
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Set<Integer> set1 = new HashSet<>();

// Add elements to the set1


set1.add(2);
set1.add(3);
System.out.println("Set1: " + set1);

// Creating another set using the HashSet class


Set<Integer> set2 = new HashSet<>();

// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);

// Union of two sets


set2.addAll(set1);
System.out.println("Union is: " + set2);
}
}

2. Implementing TreeSet Class


import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

class Setimp2 {

public static void main(String[] args) {


// Creating a set using the TreeSet class
Set<Integer> numbers = new TreeSet<>();

// Add elements to the set


numbers.add(2);
numbers.add(3);
numbers.add(1);
System.out.println("Set using TreeSet: " + numbers);

36
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Access Elements using iterator()


System.out.print("Accessing elements using iterator(): ");
Iterator<Integer> iterate = numbers.iterator();
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}

}
}

Java HashSet Class


The HashSet class of the Java Collections framework provides the functionalities of the hash table data
structure.
HashSet is the most commonly used implementation of the Set interface. It uses a hash table to store its
elements. Here are its key features:
It implements the Set interface.
1. No Duplicate Elements
2. No Order Guarantees
3. It allows only one Null Elements
4. Offers constant time Performance

Creating a HashSet

In order to create a hash set, we must import the java.util.HashSet package first.
Once we import the package, here is how we can create hash sets in Java.
1. HashSet h = new HashSet(); is the default constructor. Default initial capacity is 16, load factor is 0.75.
2. HashSet h = new HashSet(int initialCapacity) is a constructor with a given initial capacity. The load
factor is 0.75.
3. HashSet h = new HashSet(int initialCapacity, float loadFactor);is a constructor with a given initial
capacity and load factor.
4. HashSet h = new HashSet(Collection C)is a constructor that adds elements from another collection

37
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

By default,
• the capacity of the hash set will be 16
• the load factor will be 0.75

// HashSet with 8 capacity and 0.75 load factor


HashSet<Integer> numbers = new HashSet<>(8, 0.75);

Methods in HashSet

Method Description

Used to add the specified element if it is not


add(E e)
present, if it is present then return false.

clear() Used to remove all the elements from the set.

Used to return true if an element is present in a


contains(Object o)
set.

Used to remove the element if it is present in


remove(Object o)
set.

Used to return an iterator over the element in


iterator()
the set.

Used to check whether the set is empty or not.


isEmpty() Returns true for empty and false for a non-
empty condition for set.

size() Used to return the size of the set.

clone() Used to create a shallow copy of the set.

Implementation of Hashset

import java.util.*;
38
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class Hashsetimp1
{
public static void main(String[]args)
{
HashSet<String> h = new HashSet<String>();

// Add elements to the HashSet using the add() method


h.add("India");
h.add("Australia");
h.add("South Africa");
h.add("India");// try to add another same element

// Print the elements of the HashSet to the console


System.out.println(h);
System.out.println("List contains India or not:" +
h.contains("India"));

// Remove elements from the set using the remove() method


h.remove("Australia");
System.out.println("List after removing Australia:"+h);

// Loop through the elements of the HashSet using an iterator:


System.out.println("Iterating over list:");
Iterator<String> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
}

39
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Set Operations
The various methods of the HashSet class can also be used to perform various set operations.

Union of Sets
To perform the union between two sets, we can use the addAll() method. For example,
import java.util.HashSet;

class Hashsetimp2 {
public static void main(String[] args) {
HashSet<Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("HashSet1: " + evenNumbers);

HashSet<Integer> numbers = new HashSet<>();


numbers.add(1);
numbers.add(3);
System.out.println("HashSet2: " + numbers);

// Union of two set


numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);
}
}

40
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method. For example
import java.util.HashSet;

class Hashsetimp3 {
public static void main(String[] args) {
HashSet<Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("HashSet1: " + primeNumbers);

HashSet<Integer> evenNumbers = new HashSet<>();


evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("HashSet2: " + evenNumbers);

// Intersection of two sets


evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection is: " + evenNumbers);
}
}

Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method. For example,
Subset
To check if a set is a subset of another set or not, we can use the containsAll() method.

Java LinkedHashSet

The LinkedHashSet class of the Java collections framework provides functionalities of both the hashtable and
the linked list data structure.It implements the Set interface. Elements of LinkedHashSet are stored in hash
tables similar to HashSet.
41
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

However, linked hash sets maintain a doubly-linked list internally for all of its elements. The linked list defines
the order in which elements are inserted in hash tables.

We can create LinkedHashSet by using one of its four constructors. They are as follows:

1. LinkedHashSet( ): This constructor is used to create an empty LinkedHashSet. It is a default


LinkedHashSet. The general syntax to create LinkedHashSet is as follows:

LinkedHashSet<T> lhset = new LinkedHashSet<T>();

2. LinkedHashSet(Collection c): This constructor is used to initialize the LinkedHashSet with elements of
collection c. The general syntax is as follow:

LinkedHashSet<T> lhset = new LinkedHashSet<T>(Collection c);

3. LinkedHashSet(int initialCapacity): This constructor is used to create LinkedHashSet with initializing


the capacity of the linked hash set. It takes an integer value to initialize capacity. The general syntax to create
linked hash set in Java is given below:

LinkedHashSet<T> lhset = new LinkedHashSet<T>(int size);

4. LinkedHashSet(int initialCapacity, float loadFactor): This constructor is used to create LinkedHashSet


with initializing both the capacity and load factor of the linked hash set.

LinkedHashSet<T> lhset = new LinkedHashSet<T>(int initialCapacity, float loadFactor)

Methods of LinkedHashSet

The LinkedHashSet class provides methods that allow us to perform various operations on the linked hash
set.
Insert Elements to LinkedHashSet
• add() - inserts the specified element to the linked hash set
• addAll() - inserts all the elements of the specified collection to the linked hash set

Access LinkedHashSet Elements


To access the elements of a linked hash set, we can use the iterator()method. In order to use this method, we
must import the java.util.Iterator package.
Note:
• hasNext() returns true if there is a next element in the linked hash set
• next() returns the next element in the linked hash set.

Remove Elements from HashSet
• remove() - removes the specified element from the linked hash set
• removeAll() - removes all the elements from the linked hash set

42
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Union of Sets
Two perform the union between two sets, we can use the addAll() method.

Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method.

Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method.

Subset
To check if a set is a subset of another set or not, we can use the containsAll() method.

Other Methods Of LinkedHashSet:

Method Description
clone() Creates a copy of the LinkedHashSet
contains() Searches the LinkedHashSet for the specified element and returns a boolean result
isEmpty() Checks if the LinkedHashSet is empty
size() Returns the size of the LinkedHashSet
clear() Removes all the elements from the LinkedHashSet

LinkedHashSet Vs. HashSet

Both LinkedHashSet and HashSet implements the Set interface. However, there exist some differences
between them.
• LinkedHashSet maintains a linked list internally. Due to this, it maintains the insertion order of its
elements.
• The LinkedHashSet class requires more storage than HashSet. This is
because LinkedHashSet maintains linked lists internally.
• The performance of LinkedHashSet is slower than HashSet. It is because of linked lists present
in LinkedHashSet.

import java.util.Iterator;
import java.util.LinkedHashSet;

class Linkhashsetimp1
{
public static void main(String[] args) {
LinkedHashSet<Integer> evenNumber = new LinkedHashSet<>();

// Insert Elements to LinkedHashSet Using add() method


evenNumber.add(2);
evenNumber.add(4);
evenNumber.add(6);
43
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("LinkedHashSet: " + evenNumber);

LinkedHashSet<Integer> numbers = new LinkedHashSet<>();

// Insert Elements to LinkedHashSet Using addAll() method


numbers.addAll(evenNumber);
numbers.add(5);
System.out.println("New LinkedHashSet: " + numbers);

//Access LinkedHashSet Elements


// Calling the iterator() method
Iterator<Integer> iterate = numbers.iterator();

System.out.print("LinkedHashSet using Iterator: ");

// Accessing elements
while(iterate.hasNext())
{
System.out.print(iterate.next());
System.out.print(", ");
}

//Remove Elements
// Using the remove() method
boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);
boolean value2 = numbers.removeAll(numbers);
System.out.println("Are all elements removed? " + value2);
//union of two sets
LinkedHashSet<Integer> evenNum = new LinkedHashSet<>();
evenNum.add(2);
evenNum.add(4);
System.out.println("LinkedHashSet1: " + evenNum);

LinkedHashSet<Integer> num = new LinkedHashSet<>();


num.add(4);
num.add(6);
System.out.println("LinkedHashSet2: " + num);

// Union of two set


num.addAll(evenNum);
System.out.println("Union is: " + num);

//intersection of two numbers

// Intersection of two sets


44
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

num.retainAll(evenNum);
System.out.println("Intersection is: " + num);

// Difference between evenNumber and evenNum


evenNumber.removeAll(evenNum);
System.out.println("Difference : " + evenNumber);

//Subset
// Check if num is a subset of even
LinkedHashSet<Integer> even = new LinkedHashSet<>();
even.add(2);
even.add(4);
even.add(6);
boolean result = even.containsAll(num);
System.out.println("Is num is subset of even ? " + result);
}
}

Sorted Set Interface

The SortedSet interface present in java.util package extends the Set interface present in the collection
framework. It is an interface that implements the mathematical set. This interface contains the methods
inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in
a sorted manner.

45
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Creating SortedSet Objects


Since SortedSet is an interface, objects cannot be created of the type SortedSet. We always need a class which
extends this list in order to create an object.

// Obj is the type of the object to be stored in SortedSet


SortedSet<Obj> set = new TreeSet<Obj> ();

Methods of SortedSet

The SortedSet interface includes all the methods of the Set interface. It's because Set is a super interface
of SortedSet.
Besides methods included in the Set interface, the SortedSet interface also includes these methods:
• comparator() - returns a comparator that can be used to order elements in the set
• first() - returns the first element of the set
• last() - returns the last element of the set
• headSet(element) - returns all the elements of the set before the specified element
• tailSet(element) - returns all the elements of the set after the specified element including the
specified element
• subSet(element1, element2) - returns all the elements between
the element1 and element2 including element1

import java.util.SortedSet;
import java.util.TreeSet;

class Sortedsetimp1 {

public static void main(String[] args) {


// Creating SortedSet using the TreeSet
SortedSet<Integer> numbers = new TreeSet<>();

// Insert elements to the set


numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("SortedSet: " + numbers);

46
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Access the element


int firstNumber = numbers.first();
System.out.println("First Number: " + firstNumber);

int lastNumber = numbers.last();


System.out.println("Last Number: " + lastNumber);

// Remove elements
boolean result = numbers.remove(2);
System.out.println("Is the number 2 removed? " + result);
}
}

TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for
storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an
explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set
interface.
It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used.
The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.
Hierarchy Diagram of TreeSet

Creating a TreeSet

47
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

TreeSet<Integer> numbers = new TreeSet<>();


Here, we have created a TreeSet without any arguments. In this case, the elements in TreeSet are sorted
naturally (ascending order).
Methods of TreeSet
The TreeSet class provides various methods that allow us to perform various operations on the set.
Insert Elements to TreeSet
• add() - inserts the specified element to the set
• addAll() - inserts all the elements of the specified collection to the set

Access TreeSet Elements


To access the elements of a tree set, we can use the iterator() method. In order to use this method, we must
import java.util.Iterator package.
Remove Elements
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set

Methods for Navigation


Since the TreeSet class implements NavigableSet, it provides various methods to navigate over the elements
of the tree set.
1. first() and last() Methods
• first() - returns the first element of the set
• last() - returns the last element of the set
2. ceiling(), floor(), higher() and lower() Methods
• higher(element) - Returns the lowest element among those elements that are greater than the
specified element.
• lower(element) - Returns the greatest element among those elements that are less than the
specified element.
• ceiling(element) - Returns the lowest element among those elements that are greater than the
specified element. If the element passed exists in a tree set, it returns the element passed as an
argument.

48
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

• floor(element) - Returns the greatest element among those elements that are less than the
specified element. If the element passed exists in a tree set, it returns the element passed as an
argument.
3. pollfirst() and pollLast() Methods
• pollFirst() - returns and removes the first element from the set
• pollLast() - returns and removes the last element from the set

4. headSet(element, booleanValue)
The headSet() method returns all the elements of a tree set before the specified element (which is passed as an
argument).
The booleanValue parameter is optional. Its default value is false.
If true is passed as a booleanValue, the method returns all the elements before the specified element including
the specified element.
5. tailSet(element, booleanValue)
The tailSet() method returns all the elements of a tree set after the specified element (which is passed as a
parameter) including the specified element.
The booleanValue parameter is optional. Its default value is true.
If false is passed as a booleanValue, the method returns all the elements after the specified element without
including the specified element.

Set operations
The methods of the TreeSet class can also be used to perform various set operations.
Union of Sets
To perform the union between two sets, we use the addAll() method.
Intersection of Sets
To perform the intersection between two sets, we use the retainAll() method.
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method.
Subset of a Set
49
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

To check if a set is a subset of another set or not, we use the containsAll() method

TreeSet Vs. HashSet


Both the TreeSet as well as the HashSet implements the Set interface. However, there exist some differences
between them.
• Unlike HashSet, elements in TreeSet are stored in some order. It is because TreeSet implements
the SortedSet interface as well.
• TreeSet provides some methods for easy navigation. For example, first(), last(), headSet(), tailSet(),
etc. It is because TreeSet also implements the NavigableSet interface.
• HashSet is faster than the TreeSet for basic operations like add, remove, contains and size.

Map Interface in Java


In Java, Map Interface is present in java.util package represents a mapping between a key and a value. Java
Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest
of the collection types. A map contains unique keys.
Working of Map
In Java, elements of Map are stored in key/value pairs. Keys are unique values associated with
individual Values.
A map cannot contain duplicate keys. And, each key is associated with a single value.
Note: The Map interface maintains 3 different sets:
• the set of keys
• the set of values
• the set of key/value associations (mapping).
Hence we can access keys, values, and associations individually.

Classes that implement Map


Since Map is an interface, we cannot create objects from it.
In order to use the functionalities of the Map interface, we can use these classes:

50
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Interfaces that extend Map


The Map interface is also extended by these subinterfaces:

Creating Map Objects


Since Map is an interface, objects cannot be created of the type map. We always need a class that extends
this map in order to create an object.
// Map implementation using HashMap
Map<Key, Value> numbers = new HashMap<>();
Here,
• Key - a unique identifier used to associate each element (value) in a map
• Value - elements associated by keys in a map

Methods of Map

The Map interface includes all the methods of the Collection interface. It is because Collection is a super
interface of Map.
Besides methods available in the Collection interface, the Map interface also includes the following
methods:
• put(K, V) - Inserts the association of a key K and a value V into the map. If the key is already
present, the new value replaces the old value.
51
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

• putAll() - Inserts all the entries from the specified map to this map.
• putIfAbsent(K, V) - Inserts the association if the key K is not already associated with the value V.
• get(K) - Returns the value associated with the specified key K. If the key is not found, it returns null.
• getOrDefault(K, defaultValue) - Returns the value associated with the specified key K. If the key is
not found, it returns the defaultValue.
• containsKey(K) - Checks if the specified key K is present in the map or not.
• containsValue(V) - Checks if the specified value V is present in the map or not.
• replace(K, V) - Replace the value of the key K with the new specified value V.
• replace(K, oldValue, newValue) - Replaces the value of the key K with the new value newValue only
if the key K is associated with the value oldValue.
• remove(K) - Removes the entry from the map represented by the key K.
• remove(K, V) - Removes the entry from the map that has key K associated with value V.
• keySet() - Returns a set of all the keys present in a map.
• values() - Returns a set of all the values present in a map.
• entrySet() - Returns a set of all the key/value mapping present in a map.

Implementation of the Map Interface


1. Implementing HashMap Class

import java.util.Map;
import java.util.HashMap;

class Mapimp1 {

public static void main(String[] args) {


// Creating a map using the HashMap
Map<String, Integer> numbers = new HashMap<>();

// Insert elements to the map


numbers.put("One", 1);
numbers.put("Two", 2);
System.out.println("Map: " + numbers);

// Access keys of the map


System.out.println("Keys: " + numbers.keySet());
52
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Access values of the map


System.out.println("Values: " + numbers.values());

// Access entries of the map


System.out.println("Entries: " + numbers.entrySet());

// Remove Elements from the map


int value = numbers.remove("Two");
System.out.println("Removed Value: " + value);
}
}

2. Implementing TreeMap Class

import java.util.Map;
import java.util.TreeMap;

class Mapimp2 {

public static void main(String[] args) {


// Creating Map using TreeMap
Map<String, Integer> values = new TreeMap<>();

// Insert elements to map


values.put("Second", 2);
values.put("First", 1);
System.out.println("Map using TreeMap: " + values);

// Replacing the values


values.replace("First", 11);
values.replace("Second", 22);
System.out.println("New Map: " + values);

53
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Remove elements from the map


int removedValue = values.remove("First");
System.out.println("Removed Value: " + removedValue);
}
}

Java HashMap

Java HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but
there should be only one null key object and there can be any number of null values. This class makes no
guarantees as to the order of the map The HashMap class implements the Map interface.

Create a HashMap

In order to create a hash map, we must import the java.util.HashMap package first. Once we import the
package, here is how we can create hashmaps in Java.
// hashMap creation with 8 capacity and 0.6 load factor
HashMap<K, V> numbers = new HashMap<>();
Here, K represents the key type and V represents the type of values.
HashMap<String, Integer> numbers = new HashMap<>();
Here, the type of keys is String and the type of values is Integer.

54
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Note: While creating a hashmap, we can include optional parameters: capacity and load factor. For
example,
HashMap<K, V> numbers = new HashMap<>(8, 0.6f);
Here,
• 8 (capacity is 8) - This means it can store 8 entries.
• 0.6f (load factor is 0.6) - This means whenever our hash table is filled by 60%, the entries are moved
to a new hash table double the size of the original hash table.
If the optional parameters not used, then the default capacity will be 16 and the default load factor will
be 0.75.

import java.util.HashMap;

class Hashmapimp1 {
public static void main(String[] args) {

// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();

// add elements to hashmap


languages.put("Java", 8);
languages.put("JavaScript", 1);
languages.put("Python", 3);
System.out.println("HashMap: " + languages);
}
}

Basic Operations on Java HashMap


55
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

The HashMap class provides various methods to perform different operations on hashmaps.
• Add elements
• Access elements
• Change elements
• Remove elements

import java.util.HashMap;
import java.util.Map;

public class hashmapimp3 {

public static void main(String[] args) {


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

// 1. Add elements to the HashMap


map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
System.out.println("Initial HashMap: " + map);

// 2. Access an element
int value = map.get("Two");
System.out.println("Value for key 'Two': " + value);

// 3. Check if a key exists


boolean keyExists = map.containsKey("One");
System.out.println("Does key 'One' exist? " + keyExists);

// 4. Check if a value exists


boolean valueExists = map.containsValue(3);
System.out.println("Does value 3 exist? " + valueExists);

// 5. Remove an element
map.remove("One");
System.out.println("HashMap after removing key 'One': " + map);

// 6. Replace an element
map.replace("Two", 22);
System.out.println("HashMap after replacing value for key 'Two': " + map);

// 7. Iterate over elements


System.out.println("Iterating over HashMap:");
56
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

for (Map.Entry<String, Integer> entry : map.entrySet()) {


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

// 8. Size of the HashMap


int size = map.size();
System.out.println("Size of the HashMap: " + size);

// 9. Check if the HashMap is empty


boolean isEmpty = map.isEmpty();
System.out.println("Is the HashMap empty? " + isEmpty);

// 10. Clear the HashMap


map.clear();
System.out.println("HashMap after clearing: " + map);
}
}

LinkedHashMap in Java

The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of
elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it
never maintained the track and order of insertion, which the LinkedHashMap provides where the elements
can be accessed in their insertion order.

57
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Creating a LinkedHashMap

In order to create a linked hashmap, we must import the java.util.LinkedHashMap package first. Once we
import the package, here is how we can create linked hashmaps in Java.

// LinkedHashMap with initial capacity 8 and load factor 0.6

LinkedHashMap<Key, Value> numbers = new LinkedHashMap<>(8, 0.6f);

Here,
• Key - a unique identifier used to associate each element (value) in a map
• Value - elements associated by the keys in a map

Notice the part new LinkedHashMap<>(8, 0.6). Here, the first parameter is capacity and the second
parameter is loadFactor.

By default,
• the capacity of the linked hashmap will be 16
• the load factor will be 0.75

Creating LinkedHashMap from Other Maps


Here is how we can create a linked hashmap containing all the elements of other maps.

import java.util.LinkedHashMap;

class Linkhashmapimp1 {
public static void main(String[] args) {
// Creating a LinkedHashMap of even numbers
LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("LinkedHashMap1: " + evenNumbers);

// Creating a LinkedHashMap from other LinkedHashMap


LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>(evenNumbers);
58
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

numbers.put("Three", 3);
System.out.println("LinkedHashMap2: " + numbers);
}
}

Methods of LinkedHashMap

The LinkedHashMap class provides methods that allow us to perform various operations on the map.

Insert Elements to LinkedHashMap


• put() - inserts the specified key/value mapping to the map
• putAll() - inserts all the entries from the specified map to this map
• putIfAbsent() - inserts the specified key/value mapping to the map if the specified key is not present
in the map
Access LinkedHashMap Elements
1. Using entrySet(), keySet() and values()
• entrySet() - returns a set of all the key/value mapping of the map
• keySet() - returns a set of all the keys of the map
• values() - returns a set of all the values of the map
2. Using get() and getOrDefault()
• get() - Returns the value associated with the specified key. If the key is not found, it returns null.
• getOrDefault() - Returns the value associated with the specified key. If the key is not found, it returns
the specified default value.

Removed LinkedHashMap Elements


• remove(key) - returns and removes the entry associated with the specified key from the map
• remove(key, value) - removes the entry from the map only if the specified key mapped to be the
specified value and return a boolean value

Other Methods of LinkedHashMap


Method Description
clear() removes all the entries from the map
59
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

containsKey() checks if the map contains the specified key and returns a boolean value
containsValue() checks if the map contains the specified value and returns a boolean value
size() returns the size of the map
isEmpty() checks if the map is empty and returns a boolean value

LinkedHashMap Vs. HashMap

Both the LinkedHashMap and the HashMap implements the Map interface. However, there exist some
differences between them.
• LinkedHashMap maintains a doubly-linked list internally. Due to this, it maintains the insertion order
of its elements.
• The LinkedHashMap class requires more storage than HashMap. This is
because LinkedHashMap maintains linked lists internally.
• The performance of LinkedHashMap is slower than HashMap.

import java.util.LinkedHashMap;
import java.util.Map;

public class Linkedhashmapimp2


{

public static void main(String[] args) {


// Create a LinkedHashMap
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

// 1. Add elements to the LinkedHashMap


map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
System.out.println("Initial LinkedHashMap: " + map);

// 2. Access an element
int value = map.get("Two");
System.out.println("Value for key 'Two': " + value);

// 3. Check if a key exists


boolean keyExists = map.containsKey("One");
System.out.println("Does key 'One' exist? " + keyExists);

// 4. Check if a value exists


boolean valueExists = map.containsValue(3);
System.out.println("Does value 3 exist? " + valueExists);

// 5. Remove an element
map.remove("One");
60
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("LinkedHashMap after removing key 'One': " + map);

// 6. Replace an element
map.replace("Two", 22);
System.out.println("LinkedHashMap after replacing value for key 'Two': " + map);

// 7. Iterate over elements


System.out.println("Iterating over LinkedHashMap:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 8. Size of the LinkedHashMap


int size = map.size();
System.out.println("Size of the LinkedHashMap: " + size);

// 9. Check if the LinkedHashMap is empty


boolean isEmpty = map.isEmpty();
System.out.println("Is the LinkedHashMap empty? " + isEmpty);

// 10. Clear the LinkedHashMap


map.clear();
System.out.println("LinkedHashMap after clearing: " + map);

// 11. Using putIfAbsent to add an element only if it is not present


map.putIfAbsent("Four", 4);
System.out.println("LinkedHashMap after putIfAbsent: " + map);

// 12. Using computeIfPresent to modify value for a specific key if it is present


map.computeIfPresent("Four", (key, val) -> val * 2);
System.out.println("LinkedHashMap after computeIfPresent: " + map);

// 13. Using computeIfAbsent to compute value for a specific key if it is absent


map.computeIfAbsent("Five", key -> 5);
System.out.println("LinkedHashMap after computeIfAbsent: " + map);

// 14. Using forEach to iterate over elements with a lambda expression


System.out.println("Using forEach to iterate:");
map.forEach((key, val) -> System.out.println(key + ": " + val));

// 15. Using replaceAll to replace all values


map.replaceAll((key, val) -> val + 10);
System.out.println("LinkedHashMap after replaceAll: " + map);

// 16. Using entrySet to get a set view of the mappings


System.out.println("Entry set view of the mappings:");
61
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

for (Map.Entry<String, Integer> entry : map.entrySet()) {


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

TreeMap in Java

The TreeMap class of the Java collections framework provides the tree data structure implementation.

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

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.

62
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

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.

Creating a TreeMap
In order to create a TreeMap, we must import the java.util.TreeMap package first.

TreeMap<Key, Value> numbers = new TreeMap<>();

Here,
• Key - a unique identifier used to associate each element (value) in a map
• Value - elements associated by keys in a map

Methods of TreeMap
The TreeMap class provides various methods that allow us to perform operations on the map.

Methods of Java TreeMap Class


Methods Outcome
containsKey(Object key) Returns true if the map contains the specified key.
containsValue(Object
Returns true if there is any corresponding value for one or more keys in the map.
value)
put(Object key, Object
Inserts a key-value pair into the map.
value)
get(Object key) Returns the value mapped to the specified key in the map.
Removes and returns the mapping (key-value pair) with the associated key if it is
remove(Object key)
present in the TreeMap.
firstKey() Returns the first key in the sorted order of the map.
lastKey() Returns the last key (highest in the sorted order) of the TreeMap.
keySet() Returns a set view of all the keys stored in the map.
entrySet() Returns a set view of the entries (key-value mappings) in the map.
size() Returns the integer value of the total number of key-value pairs in the map.
values() Returns a collection view of all the values present in the map.
Copies all the key-value pairs from the specified map to the map for which the
putAll(Map m)
method has been called.
clear() Removes all the key-value pairs from the TreeMap.
clone() Returns a shallow copy of the specified TreeMap.

Tree Map Implementation


import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class TreeMapOperations {


63
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public static void main(String[] args) {


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

// 1. Add elements to the TreeMap


map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
System.out.println("Initial TreeMap: " + map);

// 2. Access an element
int value = map.get("Two");
System.out.println("Value for key 'Two': " + value);

// 3. Check if a key exists


boolean keyExists = map.containsKey("One");
System.out.println("Does key 'One' exist? " + keyExists);

// 4. Check if a value exists


boolean valueExists = map.containsValue(3);
System.out.println("Does value 3 exist? " + valueExists);

// 5. Remove an element
map.remove("One");
System.out.println("TreeMap after removing key 'One': " + map);

// 6. Replace an element
map.replace("Two", 22);
System.out.println("TreeMap after replacing value for key 'Two': " + map);

// 7. Iterate over elements


System.out.println("Iterating over TreeMap:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 8. Size of the TreeMap


int size = map.size();
System.out.println("Size of the TreeMap: " + size);

// 9. Check if the TreeMap is empty


boolean isEmpty = map.isEmpty();
System.out.println("Is the TreeMap empty? " + isEmpty);

// 10. Clear the TreeMap


64
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

map.clear();
System.out.println("TreeMap after clearing: " + map);

// 11. Using putIfAbsent to add an element only if it is not present


map.putIfAbsent("Four", 4);
System.out.println("TreeMap after putIfAbsent: " + map);

// 12. Using computeIfPresent to modify value for a specific key if it is present


map.computeIfPresent("Four", (key, val) -> val * 2);
System.out.println("TreeMap after computeIfPresent: " + map);

// 13. Using computeIfAbsent to compute value for a specific key if it is absent


map.computeIfAbsent("Five", key -> 5);
System.out.println("TreeMap after computeIfAbsent: " + map);

// 14. Using forEach to iterate over elements with a lambda expression


System.out.println("Using forEach to iterate:");
map.forEach((key, val) -> System.out.println(key + ": " + val));

// 15. Using replaceAll to replace all values


map.replaceAll((key, val) -> val + 10);
System.out.println("TreeMap after replaceAll: " + map);

// 16. Using entrySet to get a set view of the mappings


System.out.println("Entry set view of the mappings:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 17. Get the first and last keys


String firstKey = map.firstKey();
String lastKey = map.lastKey();
System.out.println("First key: " + firstKey);
System.out.println("Last key: " + lastKey);

// 18. Get the first and last entries


Map.Entry<String, Integer> firstEntry = map.firstEntry();
Map.Entry<String, Integer> lastEntry = map.lastEntry();
System.out.println("First entry: " + firstEntry);
System.out.println("Last entry: " + lastEntry);

// 19. Get a sub-map from the TreeMap


NavigableMap<String, Integer> subMap = map.subMap("Four", true, "Six", true);
System.out.println("Sub-map from 'Four' to 'Six': " + subMap);

// 20. Poll first and last entries


65
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Map.Entry<String, Integer> polledFirstEntry = map.pollFirstEntry();


Map.Entry<String, Integer> polledLastEntry = map.pollLastEntry();
System.out.println("Polled first entry: " + polledFirstEntry);
System.out.println("Polled last entry: " + polledLastEntry);
}
}

Hashtable class in Java

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as
a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must
implement the hashCode method and the equals method.

The Hashtable class in Java is a concrete implementation of a Dictionary and was originally part of the java.util
package. It creates a hash table by mapping keys to values

The java.util.Hashtable class is a class in Java that provides a key-value data structure, similar to the Map
interface. It was part of the original Java Collections framework and was introduced in Java 1.0.

However, the Hashtable class has since been considered obsolete and its use is generally discouraged. This is
because it was designed prior to the introduction of the Collections framework and does not implement the
Map interface, which makes it difficult to use in conjunction with other parts of the framework.

66
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

In addition, the Hashtable class is synchronized, which can result in slower performance compared to other
implementations of the Map interface.

In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap or
ConcurrentHashMap) instead of the Hashtable class.

Hashtable class declaration

Hashtable<K, V> ht = new Hashtable<K, V>();

This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11.

Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);

This creates a hash table that has an initial size specified by initialCapacity and the default load factor is
0.75.

Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio);

This version creates a hash table that has an initial size specified by size and fill ratio specified by fillRatio.
fill ratio: Basically, it determines how full a hash table can be before it is resized upward and its Value lies
between 0.0 to 1.0.

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;

public class Hashtableimp1 {

public static void main(String[] args) {


// Create a Hashtable
Hashtable<String, Integer> table = new Hashtable<>();

// 1. Add elements to the Hashtable


table.put("One", 1);
table.put("Two", 2);
table.put("Three", 3);
System.out.println("Initial Hashtable: " + table);

// 2. Access an element
int value = table.get("Two");
System.out.println("Value for key 'Two': " + value);

// 3. Check if a key exists


boolean keyExists = table.containsKey("One");
System.out.println("Does key 'One' exist? " + keyExists);
67
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// 4. Check if a value exists


boolean valueExists = table.containsValue(3);
System.out.println("Does value 3 exist? " + valueExists);

// 5. Remove an element
table.remove("One");
System.out.println("Hashtable after removing key 'One': " + table);

// 6. Replace an element
table.replace("Two", 22);
System.out.println("Hashtable after replacing value for key 'Two': " + table);

// 7. Iterate over elements using Enumeration


System.out.println("Iterating over Hashtable using Enumeration:");
Enumeration<String> keys = table.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.println(key + ": " + table.get(key));
}

// 8. Size of the Hashtable


int size = table.size();
System.out.println("Size of the Hashtable: " + size);

// 9. Check if the Hashtable is empty


boolean isEmpty = table.isEmpty();
System.out.println("Is the Hashtable empty? " + isEmpty);

// 10. Clear the Hashtable


table.clear();
System.out.println("Hashtable after clearing: " + table);

// 11. Using putIfAbsent to add an element only if it is not present


table.putIfAbsent("Four", 4);
System.out.println("Hashtable after putIfAbsent: " + table);

// 12. Using computeIfPresent to modify value for a specific key if it is present


table.computeIfPresent("Four", (key, val) -> val * 2);
System.out.println("Hashtable after computeIfPresent: " + table);

// 13. Using computeIfAbsent to compute value for a specific key if it is absent


table.computeIfAbsent("Five", key -> 5);
System.out.println("Hashtable after computeIfAbsent: " + table);

// 14. Using forEach to iterate over elements with a lambda expression


68
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("Using forEach to iterate:");


table.forEach((key, val) -> System.out.println(key + ": " + val));

// 15. Using replaceAll to replace all values


table.replaceAll((key, val) -> val + 10);
System.out.println("Hashtable after replaceAll: " + table);

// 16. Using entrySet to get a set view of the mappings


System.out.println("Entry set view of the mappings:");
for (Map.Entry<String, Integer> entry : table.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 17. Check if Hashtable contains a specific key-value mapping


boolean containsMapping = table.entrySet().contains(new
java.util.AbstractMap.SimpleEntry<>("Four", 14));
System.out.println("Does Hashtable contain the mapping 'Four'=14? " + containsMapping);
}
}

Sorting in Java

The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or
descending order. The numerical and lexicographical (alphabetical) order is a widely used order.

Java provides several built-in methods and algorithms for sorting arrays efficiently.

Approaches for Sorting Elements in an Array in Java

69
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Approach 1: Without using Method


• Using Loops
• Using the user defined method
Approach 2: Using Arrays.sort()
Approach 3 : Using Sort Method of Collection class
Approach 4: Sorting on a subarray

Approach 1 Using Loops

public class sortingimp1


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

//Initialize array
int [] arr = new int [] {10, 40, 30, 20};
int temp = 0;

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

//Displaying elements of array after sorting


for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}

70
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Approach 2: Using Arrays.sort()

Java provides a built-in method, Arrays.sort(), to sort an array. This method sorts the array’s elements into
ascending order, applicable to different types of arrays such as integer, double, string, or custom objects.
The Arrays.sort() method uses a variation of the QuickSort algorithm, known for its efficiency in most
common scenarios.

import java.util.Arrays;

// Main class
public class sortingimp2
{

// Main driver method


public static void main(String[] args)
{
// Custom input array
int[] arr = { 10,40,30,20 };

// Calling the sort() method present


// inside Arrays class
Arrays.sort(arr);

// Printing and display sorted array


System.out.printf("Modified arr[] : %s", Arrays.toString(arr));
}
}

Approach 3: Using Collection.sort()

// Java program to demonstrate working of Collections.sort()


import java.util.*;

public class sortingimp3


{
public static void main(String[] args)
{
// Create a list of strings
ArrayList<String> al = new ArrayList<String>();
al.add("JAVA");
al.add("FORTRAN");
71
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

al.add("DBMS");
al.add("HTML");
al.add("SQL");

/* Collections.sort method is sorting the


elements of ArrayList in ascending order. */
Collections.sort(al);

// Let us print the sorted list


System.out.println("List after the use of" + " Collection.sort() :\n" + al);
}
}

Approach 4: Sorting on Subarray

import java.util.Arrays;

// Main class
public class sortingimp4
{

// Main drive method


public static void main(String[] args)
{
// Custom input array
int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };

// Sort subarray from index 1 to 4, i.e.,


// only sort subarray {7, 6, 45, 21} and
// keep other elements as it is.
Arrays.sort(arr, 1, 5);

// Printing sorted array


System.out.printf("Modified arr[] : %s",Arrays.toString(arr));
}
}
72
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Using the reverseOrder() Method


Java Collections class provides the reverseOrder() method to sort the array in reverse-lexicographic order.
It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It
returns a comparator that imposes the reverse of the natural ordering (ascending order).
import java.util.Arrays;
import java.util.Collections;
public class sortingimp5
{
public static void main(String[] args)
{
Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205};
// sorts array[] in descending order
Arrays.sort(array, Collections.reverseOrder());
System.out.println("Array elements in descending order: " +Arrays.toString(array));
}
}

Note:
• Which sorting algorithm does Java use in sort()?

73
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for
arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort.

• Which order of sorting is done by default?

It by default sorts in ascending order.

• How to sort array or list in descending order?

It can be done with the help of Collections.reverseOrder().

Comparable Interface

The Comparable interface is used to compare an object of the same class with an instance of that class, it
provides ordering of data for objects of the user-defined class. The class has to implement
the java.lang.Comparable interface to compare its instance, it provides the compareTo method that takes a
parameter of the object of that class.

The compareTo method required by the Comparable interface receives as its parameter the object to which
the "this" object is compared.
If the "this" object comes before the object received as a parameter in terms of sorting order, the method should
return a negative number.
If, on the other hand, the "this" object comes after the object received as a parameter, the method should return
a positive number. Otherwise, 0 is returned.
The sorting resulting from the compareTo method is called natural ordering

Using Comparable Interface


• Implement the Comparable interface from java.lang Package in a class.
• The Comparable interface contains the method compareTo to decide the order of the elements.
• Override the compareTo method in a class.
• Create an array of class and populate the array.
• Use the Arrays.sort() function to sort the array.

Syntax
class MyClass implements Comparable<MyClass> {
// Class body.
...
@Override public int compareTo(MyClass value)
74
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
// Comparison Logic
...
return result;
}
}
This interface has a single .compareTo() method that returns an int value based on whether the value of a
current class instance (referenced by this) can be logically sorted with the value of another instance of the
same class.
The compareTo method should follow the contract defined by the Comparable interface. The comparison
logic should be consistent with the equals method (i.e., if compareTo returns 0, equals should return true).
Return Value Meaning
>= 1 this instance > passed instance
0 this instance = passed instance
<= -1 this instance < passed instance

Implementation
Given an array of Pairs consisting of two fields of type string and integer. you have to sort the array in
ascending Lexicographical order and if two strings are the same sort it based on their integer value.
Sample I/O:
Input: { {"abc", 3}, {"a", 4}, {"bc", 5}, {"a", 2} }
Output: { {"a", 2}, {"a", 4}, {"abc", 3}, {"bc", 5} }

Input: { {"efg", 1}, {"gfg", 1}, {"cba", 1}, {"zaa", 1} }


Output: { {"cba", 1}, {"efg", 1}, {"gfg", 1}, {"zaa", 1} }

Implemenation-1
import java.io.*;
import java.util.*;

75
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class Member implements Comparable<Member> {


String x;
int y;

public Member(String x, int y)


{
this.x = x;
this.y = y;
}

public String toString()


{
return "(" + x + "," + y + ")";
}

@Override public int compareTo(Member a)


{
// if the string are not equal
if (this.x.compareTo(a.x) != 0) {
return this.x.compareTo(a.x);
}
else {
// we compare int values
// if the strings are equal
return this.y - a.y;
}
}
}

public class Comparableimp1 {


public static void main(String[] args)
{

int n = 4;
Member arr[] = new Member[n];

arr[0] = new Member("abc", 3);


arr[1] = new Member("a", 4);
arr[2] = new Member("bc", 5);
arr[3] = new Member("a", 2);

// Sorting the array


Arrays.sort(arr);

// printing the
// Pair array
76
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

print(arr);
}

public static void print(Member[] arr)


{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

Implemenation-2

import java.io.*;
import java.util.*;

class Member1 implements Comparable<Member1> {


String x;
int y;

public Member1(String x, int y)


{
this.x = x;
this.y = y;
}

public String toString()


{
return "(" + x + "," + y + ")";
}

@Override public int compareTo(Member1 a)


{
// if the string are not equal
if (this.x.compareTo(a.x) != 0) {
return this.x.compareTo(a.x);
}
else {
// we compare int values
// if the strings are equal
77
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

return this.y - a.y;


}
}
}

public class Comparatorimp2 {


public static void main(String[] args)
{

int n = 4;
Member1 arr[] = new Member1[n];

arr[0] = new Member1("efg", 1);


arr[1] = new Member1("gfg", 1);
arr[2] = new Member1("cba", 1);
arr[3] = new Member1("zaa", 1);

// Sorting the array


Arrays.sort(arr);

// printing the
// Pair array
print(arr);
}

public static void print(Member1[] arr)


{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

Example 2
Given an array of Pairs consisting of two strings with first and last names. you have to sort the array in
ascending Lexicographical order of the first name and if two strings are the same sort it based on their last
name.
Sample I/O:
Input: { {"raj", "kashup"}, {"rahul", "singh"}, {"reshmi", "dubey"}, {"rahul", "jetli"} }
Output: { {"rahul", "jetli"}, {"rahul", "singh"}, {"raj", "kashup"}, {"reshmi", "dubey"} }
78
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Input: { {"abc", "last"}, {"pklz", "yelp"}, {"rpng", "note"}, {"ppza", "xyz"} }


Output: { {"abc", "last"}, {"pklz", "yelp"}, {"ppza", "xyz"}, {"rpng", "note"}

import java.io.*;
import java.util.*;

class Member3 implements Comparable<Member3>


{
String firstName;
String lastName;

public Member3(String x, String y)


{
this.firstName = x;
this.lastName = y;
}

public String toString()


{
return "( " + firstName + " , " + lastName + " )";
}

@Override public int compareTo(Member3 a)


{
// if the string are not equal
if (this.firstName.compareTo(a.firstName) != 0) {
return this.firstName.compareTo(a.firstName);
}
else {
// we compare lastName if firstNames are equal
return this.lastName.compareTo(a.lastName);
}
}
}

public class Comparableimp3 {


public static void main(String[] args)
{

int n = 4;
Member3 arr[] = new Member3[n];
arr[0] = new Member3("raj", "kashup");
arr[1] = new Member3("rahul", "singh");
arr[2] = new Member3("reshmi", "dubey");
arr[3] = new Member3("rahul", "jetli");
79
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Sorting the array


Arrays.sort(arr);

// printing the
// Pair array
print(arr);
}

public static void print(Member3[] arr)


{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

Comparator Interface in Java

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 –
1. compare(Object obj1,Object obj2)
2. equals(Object element).
It provides multiple sorting sequences, i.e., we can sort the elements on the basis of any data member, for
example, rollno, name, age or anything else.

Syntax
class MyComparator implements Comparator<MyClass> {
@Override public int compare(MyClass a, MyClass b)
{
// Compare logic
...

80
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

return result;
}
}

Applying the Comparator interface to a class, MyComparator, requires the implements keyword
(e.g., Comparator<MyClass>). This interface has a .compare() method that returns an int value based on
whether two MyClass instances, a and b, can be logically sorted.

Return Value Meaning

>= 1 first object instance > second object instance

0 first object instance = second object instance

<= -1 first object instance < second object instance

A Comparator class can be passed as an argument to methods such as Arrays.sort() and Collections.sort() to
specify the sort order, potentially overriding the natural sort order defined by the class’s
own .compareTo() method.

Methods of Java Comparator Interface

Method Description
public int compare(Object obj1, Object obj2) It compares the first object with the second object.
public boolean equals(Object obj) It is used to compare the current object with the specified
object.

// Java Program to Demonstrate Working of


// Comparator Interface Via More than One Field

// Importing required classes


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

// Class 1
// Helper class representing a Student
81
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class Student {

// Attributes of student
String Name;
int Age;

// Parameterized constructor
public Student(String Name, Integer Age)
{

// This keyword refers to current instance itself


this.Name = Name;
this.Age = Age;
}

// Getter setter methods


public String getName() { return Name; }

public void setName(String Name) { this.Name = Name; }

public Integer getAge() { return Age; }

public void setAge(Integer Age) { this.Age = Age; }

// Method
// Overriding toString() method
@Override public String toString()
{
return "Customer{"
+ "Name=" + Name + ", Age=" + Age + '}';
}
}

// Class 2
// Helper class implementing Comparator interface
class CustomerSortingComparator implements Comparator<Student>
{

// Method 1
// To compare customers
@Override
public int compare(Student customer1, Student customer2)
{

// Comparing customers
int NameCompare = customer1.getName().compareTo(customer2.getName());
82
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

int AgeCompare = customer1.getAge().compareTo(customer2.getAge());

// 2nd level comparison


return (NameCompare == 0) ? AgeCompare : NameCompare;
}
}

// Method 2
// Main driver method
class comparatorinterfaceimp1
{
public static void main(String[] args)
{

// Create an empty ArrayList


// to store Student
List<Student> al = new ArrayList<>();

// Create customer objects


// using constructor initialization
Student obj1 = new Student("Ajay", 27);
Student obj2 = new Student("Sneha", 23);
Student obj3 = new Student("Simran", 37);
Student obj4 = new Student("Ajay", 22);
Student obj5 = new Student("Ajay", 29);
Student obj6 = new Student("Sneha", 22);

// Adding customer objects to ArrayList


// using add() method
al.add(obj1);
al.add(obj2);
al.add(obj3);
al.add(obj4);
al.add(obj5);
al.add(obj6);

// Iterating using Iterator


// before Sorting ArrayList
Iterator<Student> custIterator = al.iterator();

// Display message
System.out.println("Before Sorting:\n");

// Holds true till there is single element


// remaining in List
83
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

while (custIterator.hasNext()) {

// Iterating using next() method


System.out.println(custIterator.next());
}

// Sorting using sort method of Collections class


Collections.sort(al,new CustomerSortingComparator());

// Display message only


System.out.println("\n\nAfter Sorting:\n");

// Iterating using enhanced for-loop


// after Sorting ArrayList
for (Student customer : al) {
System.out.println(customer);
}
}
}

Properties class in Java

Properties class is the child class of Hashtable. It works in conjunction with properties file which is a text
file. A properties file contains key-value in text format.
The Properties class in Java is a subclass of Hashtable that is used to maintain lists of values in which the key
is a string and the value is also a string. This class is often used for configuration and storing settings for
applications.
The Properties class is a powerful tool for managing application configuration and settings, making it easy to
load, save, and manipulate key-value pairs in your Java applications.

84
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Properties class get us access to properties file.


Constructors
There are two types of constructors in the Properties class, which are as follows:
# Properties() as a constructor
Properties() constructor is a constructor used to create properties object with no default values.
# Properties(Properties Default) as a constructor
Properties(Properties Default) creates an object that uses its default values as propDefault. But in any case,
whether it is Properties() as a constructor or Properties() as a constructor, the property list will be empty only.

Methods
Java Properties is a type of class which includes the following methods within it:
• String getProperty(String Key)
• String getProperty(String key, String defaultProperty)
• voidList(PrintStream streamOut)
• voidList(PrintWriter streamOut)
• voidload(InputStream streamIn) throws IO Exception
• Enumeration propertyNames()
• ObjectSetProerty(String key, StringValue)
• void store(Output Stream streamOut, String Description)

Examples of Properties Class in Java

import java.util.*;
public class Propertyclassimp1
{
public static void main(String arg[])
{
Properties ex = new Properties();
Set url;
String str;

85
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

ex.put("aktu", "aktu.ac.in");
ex.put("result", "result.aktu.ac.in");
ex.put("syllabus", "syllabus.result.aktu.ac.in");
url = ex.keySet();
Iterator itr = url.iterator();
while(itr.hasNext())
{
str = (String)itr.next();
System.out.println("The url for " + str + " is " + ex.getProperty(str));
}
System.out.println();
str = ex.getProperty("syllabus", "not found");
System.out.println("This is the respective url for the syllabus " + str);
}
}

Example 2: The below program shows how to use the Properties class to get all the system properties.
Using System.getProperties() method, we can get all the properties of the system.

// Java program to demonstrate Properties class to get all


// the system properties

import java.util.*;
import java.io.*;

public class GFG {


public static void main(String[] args) throws Exception
{
// get all the system properties
Properties p = System.getProperties();

// stores set of properties information


Set set = p.entrySet();

// iterate over the set


Iterator itr = set.iterator();
while (itr.hasNext()) {
86
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// print each property


Map.Entry entry = (Map.Entry)itr.next();
System.out.println(entry.getKey() + " = "
+ entry.getValue());
}
}
}

Basic Operations with Properties

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class Propertyclassimp3 {

public static void main(String[] args) {


// Create a Properties object
Properties properties = new Properties();

// Set properties
87
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

properties.setProperty("username", "admin");
properties.setProperty("password", "12345");

// Save properties to a file


try (FileOutputStream out = new FileOutputStream("config.properties")) {
properties.store(out, "User Settings");
} catch (IOException e) {
e.printStackTrace();
}

// Load properties from a file


Properties loadedProperties = new Properties();
try (FileInputStream in = new FileInputStream("config.properties")) {
loadedProperties.load(in);
} catch (IOException e) {
e.printStackTrace();
}

// Access properties
String username = loadedProperties.getProperty("username");
String password = loadedProperties.getProperty("password");

System.out.println("Loaded Properties:");
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}

88
SUDHAKAR DWIVEDI,IMSEC,CSE

You might also like