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

UNIT 1

The document provides an overview of design patterns in software development, emphasizing their role as best practices derived from the experiences of expert developers. It introduces the Gang of Four (GOF) and categorizes design patterns into Core Java and JEE patterns, detailing various types such as Creational, Factory Method, Prototype, and Singleton patterns. Each pattern is explained with its advantages, usage scenarios, and examples to illustrate their implementation.

Uploaded by

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

UNIT 1

The document provides an overview of design patterns in software development, emphasizing their role as best practices derived from the experiences of expert developers. It introduces the Gang of Four (GOF) and categorizes design patterns into Core Java and JEE patterns, detailing various types such as Creational, Factory Method, Prototype, and Singleton patterns. Each pattern is explained with its advantages, usage scenarios, and examples to illustrate their implementation.

Uploaded by

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

UNIT-I

1.1 DESIGN PATTERNS

1.1.1 INTRODUCTION TO DESIGN PATTERNS

Design patterns represent the best practices used by experienced


object-oriented software developers. Design patterns are solutions to
general problems that software developers faced during software
development. These solutions were obtained by trial and error by numerous
software developers over quite a substantial period of time.
What is Gang of Four (GOF)?

In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides published a book titled Design Patterns - Elements of
Reusable Object-Oriented Software which initiated the concept of Design
Pattern in Software development.

These authors are collectively known as Gang of Four (GOF). According


to these authors design patterns are primarily based on the following
principles of object orientated design.

 Program to an interface not an implementation

 Favor object composition over inheritance


Usage of Design Pattern

Design Patterns have two main usages in software development.


Common platform for developers

Design patterns provide a standard terminology and are specific to particular scenario.
For example, a singleton design pattern signifies use of single object so all developers familiar
with single design pattern will make use of single object and they can tell each other that
program is following a singleton pattern.
Best Practices

Design patterns have been evolved over a long period of time and they
provide best solutions to certain problems faced during software
development. Learning these patterns helps unexperienced developers to
learn software design in an easy and faster way.
Advantage of design pattern

 They are reusable in multiple projects.


 They provide the solutions that help to define the system architecture.
 They capture the software engineering experiences.
 They provide transparency to the design of an application.
 They are well-proved and testified solutions since they have been built
upon the knowledge and experience of expert software developers.
 Design patterns don?t guarantee an absolute solution to a problem.
They provide clarity to the system architecture and the possibility of
building a better system.

1.1.2 CATALOGUE FOR DESIGN PATTERN


We must use the design patterns during the analysis and
requirement phase of SDLC(Software Development Life Cycle).Design
patterns ease the analysis and requirement phase of SDLC by providing
information based on prior hands-on experiences.Basically, design patterns
are categorized into two parts:

 Core Java (or JSE) Design Patterns.


 JEE Design Patterns.
Core Java Design Patterns

In core java, there are mainly three types of design patterns, which are
further divided into their sub-parts:

Creational design patterns

Creational design patterns are concerned with the way of creating


objects. These design patterns are used when a decision must be made at
the time of instantiation of a class (i.e. creating an object of a class).But
everyone knows an object is created by using new keyword in java. For
example
StudentRecord s1=new StudentRecord();

Hard-Coded code is not the good programming approach. Here,


we are creating the instance by using the new keyword. Sometimes, the
nature of the object must be changed according to the nature of the
program. In such cases, we must get the help of creational design patterns
to provide more general and flexible approach.
Types of creational design patterns

There are following 6 types of creational design patterns.

 Factory Method Pattern

 Abstract Factory Pattern

 Singleton Pattern

 Prototype Pattern

 Builder Pattern

 Object Pool Pattern

1.1.3 FACTORY METHOD PATTERN


A Factory Pattern or Factory Method Pattern says that just define an
interface or abstract class for creating an object but let the subclasses
decide which class to instantiate. In other words, subclasses are responsible
to create the instance of the class.The Factory Method Pattern is also known
as Virtual Constructor.
Advantage of Factory Design Pattern

 Factory Method Pattern allows the sub-classes to choose the type of


objects to create.
 It promotes the loose-coupling by eliminating the need to bind
application-specific classes into the code. That means the code
interacts solely with the resultant interface or abstract class, so that it
will work with any classes that implement that interface or that
extends that abstract class.
Usage of Factory Design Pattern

 When a class doesn't know what sub-classes will be required to create

 When a class wants that its sub-classes specify the objects to be


created.

 When the parent classes choose the creation of objects to its sub-
classes.

UML for Factory Method Pattern

 We are going to create a Plan abstract class and concrete classes that
extends the Plan abstract class. A factory class GetPlanFactory is
defined as a next step.

 GenerateBill class will use GetPlanFactory to get a Plan object. It will


pass information(DOMESTIC PLAN/COMMERCIAL PLAN/ INSTITUTIONAL
PLAN) to GetPalnFactory to get the type of object it needs.
Calculate Electricity Bill : A Real World Example of Factory Method

Step 1: Create a Plan abstract class.


import java.io.*;
abstract class Plan{
protected double rate;
abstract void getRate();
public void calculateBill(int units){
System.out.println(units*rate);
}
}//end of Plan class.
Step 2: Create the concrete classes that extends Plan abstract class.
class DomesticPlan extends Plan{
//@override
public void getRate(){
rate=3.50;
}
}//end of DomesticPlan class.
class CommercialPlan extends Plan{
//@override
public void getRate(){
rate=7.50;
}
/end of CommercialPlan class.
class InstitutionalPlan extends Plan{
//@override
public void getRate(){
rate=5.50;
} /end of InstitutionalPlan class.
Step 3: Create a GetPlanFactory to generate object of concrete classes based
on given information..
class GetPlanFactory{
//use getPlan method to get object of type Plan
public Plan getPlan(String planType){
if(planType == null){
return null;
}
if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
return new DomesticPlan();
}
else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){
return new CommercialPlan();
}
else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
return new InstitutionalPlan();
}
return null;
}
}//end of GetPlanFactory class.
Step 4: Generate Bill by using the GetPlanFactory to get the object of
concrete classes by passing an information such as type of plan
DOMESTICPLAN or COMMERCIALPLAN or INSTITUTIONALPLAN.
import java.io.*;
class GenerateBill{
public static void main(String args[])throws IOException{
GetPlanFactory planFactory = new GetPlanFactory();
System.out.print("Enter the name of plan for which the bill will be gen
erated: ");
BufferedReader br=new BufferedReader(new InputStreamReader(Syst
em.in)); String planName=br.readLine();
System.out.print("Enter the number of units for bill will be calculated:
");
int units=Integer.parseInt(br.readLine());
Plan p = planFactory.getPlan(planName);
//call getRate() method and calculateBill()method of DomesticPaln.
System.out.print("Bill amount for "+planName+" of "+units+" units
is: "); p.getRate();
p.calculateBill(units);
}
}//end of GenerateBill class.
Output
1.1.4 PROTOTYPE PATTERN
Prototype Pattern says that cloning of an existing object instead of
creating new one and can also be customized as per the requirement. This
pattern should be followed, if the cost of creating a new object is expensive
and resource intensive.
Advantage of Prototype Pattern

The main advantages of prototype pattern are as follows:

 It reduces the need of sub-classing.

 It hides complexities of creating objects.

 The clients can get new objects without knowing which type of object it
will be.
 It lets you add or remove objects at runtime.
Usage of Prototype Pattern

 When the classes are instantiated at runtime.


 When the cost of creating an object is expensive or complicated.
 When you want to keep the number of classes in an application
minimum.
 When the client application needs to be unaware of object creation and
representation.UML for Prototype Pattern
• We are going to create an interface Prototype that contains a method
getClone() of Prototype type.
• Then, we create a concrete class EmployeeRecord which implements
Prototype interface that does the cloning of EmployeeRecord object.
• PrototypeDemo class will uses this concrete class EmployeeRecord
Example of Prototype Design Pattern

Let's see the example of prototype design pattern.


File: Prototype.java
interface Prototype {
public Prototype getClone();
}//End of Prototype interface

File: EmployeeRecord.java
class EmployeeRecord implements Prototype{
private int id;
private String name, designation;
private double salary;
private String address;
public EmployeeRecord(){
System.out.println(" Employee Records of Oracle Corporation ");
System.out.println("---------------------------------------------");
System.out.println("Eid"+"\t"+"Ename"+"\t"+"Edesignation"+"\
t"+"Esalary"+"\t\t"+"Eaddress");
}
public EmployeeRecord(int id, String name, String designation, double s
alary, String address) {
this();
this.id = id;
this.name = name;
this.designation = designation;
this.salary = salary;
this.address = address; }
public void showRecord(){
System.out.println(id+"\t"+name+"\t"+designation+"\t"+salary+"\
t"+address); }
@Override
public Prototype getClone() {
return new EmployeeRecord(id,name,designation,salary,addre
ss);
}
}//End of EmployeeRecord class.
File: PrototypeDemo.java

Import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Class PrototypeDemo{
public static void main(String[] args) throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System
.in)); System.out.print("Enter Employee Id: ");
int eid=Integer.parseInt(br.readLine());
System.out.print("\n");
System.out.print("Enter Employee Name: ");
String ename=br.readLine();
System.out.print("\n");
System.out.print("Enter Employee Designation: ");
String edesignation=br.readLine();
System.out.print("\n");
System.out.print("Enter Employee Address: ");
String eaddress=br.readLine();
System.out.print("\n");
System.out.print("Enter Employee Salary: ");
double esalary= Double.parseDouble(br.readLine());
System.out.print("\n");
EmployeeRecord e1=new EmployeeRecord(eid,ename,edesignation,esala
ry,eaddress);
e1.showRecord();
System.out.println("\n");
EmployeeRecord e2=(EmployeeRecord) e1.getClone();
e2.showRecord();
} }//End of the ProtoypeDemo class.
Output:

1.1.5 Singleton pattern


Singleton Pattern says that just"define a class that has only one
instance and provides a global point of access to it".In other words, a class
must ensure that only single instance should be created and single object
can be used by all other classes.
There are two forms of singleton design pattern
 Early Instantiation: creation of instance at load time.
 Lazy Instantiation: creation of instance when required.

Advantage of Singleton design pattern

Saves memory because object is not created at each request. Only


single instance is reused again and again.
Usage of Singleton design pattern

Singleton pattern is mostly used in multi-threaded and database


applications. It is used in logging, caching, thread pools, configuration
settings etc.
UML of Singleton design pattern

How to create Singleton design pattern?

To create the singleton class, we need to have static member of class,


private constructor and static factory method.

 Static member: It gets memory only once because of static, itcontains


the instance of the Singleton class.

 Private constructor: It will prevent to instantiate the Singleton class


from outside the class.

 Static factory method: This provides the global point of access to the
Singleton object and returns the instance to the caller.
Understanding early Instantiation of Singleton Pattern

In such case, we create the instance of the class at the time of


declaring the static data member, so instance of the class is created at the
time of classloading.Let's see the example of singleton design pattern using
early instantiation.
File: A.java

class A
{
private static A obj=new A();//Early, instance will be created at load time
private A(){}
public static A getA(){
return obj;
}
public void doSomething(){
//write your code
} }
Understanding lazy Instantiation of Singleton Pattern

In such case, we create the instance of the class in synchronized


method or synchronized block, so instance of the class is created when
required.Let's see the simple example of singleton design pattern using lazy
instantiation.
File: A.javaclass A

{
private static A obj;
private A(){}
public static A getA(){
if (obj == null){
synchronized(Singleton.class){
if (obj == null){
obj = new Singleton();//instance will be created at request time
}
}
}
return obj;
}
public void doSomething(){
//write your code

} }
Significance of Serialization in Singleton Pattern

If singleton class is Serializable, you can serialize the singleton


instance. Once it is serialized, you can deserialize it but it will not return the
singleton object.To resolve this issue, you need to override the readResolve()
method that enforces the singleton. It is called just after the object is
deserialized. It returns the singleton object.
public class A implements Serializable {
//your code of singleton
protected Object readResolve() {
return getA();
} }
Understanding Real Example of Singleton Pattern

We are going to create a JDBCSingleton class. This JDBCSingleton class


contains its constructor as private and a private static instance jdbc of
itself.JDBCSingleton class provides a static method to get its static instance
to the outside world. Now, JDBCSingletonDemo class will use JDBCSingleton
class to get the JDBCSingleton object.
Assumption: you have created a table userdata that has three fields
uid, uname and upassword in mysql database. Database name is
ashwinirajput, username is root, password is ashwini.

File: JDBCSingleton.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class JDBCSingleton {
//Step 1
// create a JDBCSingleton class.
//static member holds only one instance of the JDBCSingleton class.
private static JDBCSingleton jdbc;
//JDBCSingleton prevents the instantiation from any other class.
private JDBCSingleton() { }
//Now we are providing gloabal point of access.
public static JDBCSingleton getInstance() {
if (jdbc==null)
{
jdbc=new JDBCSingleton();
}
return jdbc;
}
// to get the connection from methods like insert, view etc.
private static Connection getConnection()throws ClassNotFoundExcept
ion, SQLException
{
Connection con=null;
Class.forName("com.mysql.jdbc.Driver");
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/
ashwanirajput", "root", "ashwani");
return con;
}
//to insert the record into the database
public int insert(String name, String pass) throws SQLException
{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement("insert into userdata(uname,upasswor
d)values(?,?)");
ps.setString(1, name);
ps.setString(2, pass);
recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); } finally{

if (ps!=null){
ps.close();
}if(c!=null){
c.close();
} }
return recordCounter;
}
//to view the data from the database
public void view(String name) throws SQLException
{ Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try { con=this.getConnection();
ps=con.prepareStatement("select * from userdata where una
me=?");
ps.setString(1, name);
rs=ps.executeQuery();
while (rs.next()) {
System.out.println("Name= "+rs.getString(2)+"\t"+"Paasword= "+rs.get
String(3)); }
} catch (Exception e) { System.out.println(e);}

finally{
if(rs!=null){
rs.close();
}if (ps!=null){
ps.close();
}if(con!=null){
con.close();
} } }
// to update the password for the given username
public int update(String name, String password) throws SQLException {
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement(" update userdata set upassword=? w
here uname='"+name+"' ");
ps.setString(1, password);
recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); } finally{
if (ps!=null){
ps.close();
}if(c!=null){

c.close();
}
}
return recordCounter;
}
// to delete the data from the database
public int delete(int userid) throws SQLException{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement(" delete from userdata where uid='"+
userid+"' "); recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); }
finally{
if (ps!=null){
ps.close();
}if(c!=null){

c.close();
}
}
return recordCounter;
} }// End of JDBCSingleton class

File: JDBCSingletonDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class JDBCSingletonDemo{
static int count=1;
static int choice;
public static void main(String[] args) throws IOException {
JDBCSingleton jdbc= JDBCSingleton.getInstance();
BufferedReader br=new BufferedReader(new InputStreamReader(Syste
m.in));
do{
System.out.println("DATABASE OPERATIONS");
System.out.println(" --------------------- ");
System.out.println(" 1. Insertion ");
System.out.println(" 2. View ");
System.out.println(" 3. Delete ");
System.out.println(" 4. Update ");
System.out.println(" 5. Exit ");
System.out.print("\n");
System.out.print("Please enter the choice what you want to perform in t
he database: ");
choice=Integer.parseInt(br.readLine());
switch(choice) {
case 1:{
System.out.print("Enter the username you want to insert data in
to the database: ");
String username=br.readLine();
System.out.print("Enter the password you want to insert data int
o the database: ");
String password=br.readLine();
try {
int i= jdbc.insert(username, password);
if (i>0) {
System.out.println((count++) + " Data has been inserted suc
cessfully");
}else{
System.out.println("Data has not been inserted ");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}//End of case 1
break;
case 2:{
System.out.print("Enter the username : ");
String username=br.readLine();
try {
jdbc.view(username);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}//End of case 2
break;
case 3:{
System.out.print("Enter the userid, you want to delete: ");
int userid=Integer.parseInt(br.readLine());
try {
int i= jdbc.delete(userid);
if (i>0) {
System.out.println((count++) + " Data has been deleted su
ccessfully");
}else{
System.out.println("Data has not been deleted");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}//End of case 3
break;
case 4:{
System.out.print("Enter the username, you want to update: ");
String username=br.readLine();
System.out.print("Enter the new password ");
String password=br.readLine();
try {
int i= jdbc.update(username, password);
if (i>0) {
System.out.println((count++) + " Data has been updated suc
cessfully );
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}// end of case 4
break;
default:
return;
}
} while (choice!=4); } }
output:
1.1.6 ADAPTER PATTERN
An Adapter Pattern says that just "converts the interface of a class into
another interface that a client wants".In other words, to provide the interface
according to client requirement while using the services of a class with a
different interface.The Adapter Pattern is also known as Wrapper.
Advantage of Adapter Pattern

 It allows two or more previously incompatible objects to interact.

 It allows reusability of existing functionality.

Usage of Adapter pattern:

It is used:
 When an object needs to utilize an existing class with an incompatible
interface.
 When you want to create a reusable class that cooperates with classes
which don't have compatible interfaces.
 When you want to create a reusable class that cooperates with classes
which don't have compatible interfaces
Example of Adapter Pattern

Let's understand the example of adapter design pattern by the below


UML diagram.There are the following specifications for the adapter pattern:
 Target Interface: This is the desired interface class which will be used
by the clients.
 Adapter class: This class is a wrapper class which implements the
desired target interface and modifies the specific request available
from the Adaptee class.
 Adaptee class: This is the class which is used by the Adapter class to
reuse the existing functionality and modify them for desired use.
 Client: This class will interact with the Adapter class.

Implementation of above UML:

Step 1: Create a CreditCard interface (Target interface).


public interface CreditCard {
public void giveBankDetails();
public String getCreditCard();
}// End of the CreditCard interface.
Step 2:Create a BankDetails class (Adaptee class).
File: BankDetails.java
// This is the adapter class.
public class BankDetails{
private String bankName;
private String accHolderName;
private long accNumber;
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getAccHolderName() {
return accHolderName;
} public void setAccHolderName(String accHolderName) {
this.accHolderName = accHolderName;
} public long getAccNumber() {
return accNumber;
} public void setAccNumber(long accNumber) {
this.accNumber = accNumber;
} }// End of the BankDetails class.
Step 3: Create a BankCustomer class (Adapter class).
File: BankCustomer.java
// This is the adapter class
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BankCustomer extends BankDetails implements CreditCard {
public void giveBankDetails(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.i
n));
System.out.print("Enter the account holder name :");
String customername=br.readLine();
System.out.print("\n");
System.out.print("Enter the account number:");
long accno=Long.parseLong(br.readLine());
System.out.print("\n");
System.out.print("Enter the bank name :");
String bankname=br.readLine();
setAccHolderName(customername);
setAccNumber(accno);
setBankName(bankname);
}catch(Exception e){
e.printStackTrace();
} }
@Override
public String getCreditCard() {
long accno=getAccNumber();
String accholdername=getAccHolderName();
String bname=getBankName();
return ("The Account number "+accno+" of "+accholdername+" in "+bna
me+ "
bank is valid and authenticated for issuing the credit card. ");
}
}//End of the BankCustomer class.
Step 4
Create a AdapterPatternDemo class (client class).
File: AdapterPatternDemo.java
//This is the client class.
public class AdapterPatternDemo {
public static void main(String args[]){
CreditCard targetInterface=new BankCustomer();
targetInterface.giveBankDetails();
System.out.print(targetInterface.getCreditCard());
}
}//End of the BankCustomer class.
Output
Enter the account holder name :Sonoo Jaiswal
Enter the account number:10001
Enter the bank name :State Bank of India
The Account number 10001 of Sonoo Jaiswal in State Bank of India bank is
valid
and authenticated for issuing the credit card.

1.1.7 PROXY PATTERN


Simply, proxy means an object representing another object.According
to GoF, a Proxy Pattern "provides the control for accessing the original
object".So, we can perform many operations like hiding the information of
original object, on demand loading etc.Proxy pattern is also known
as Surrogate or Placeholder.
Advantage of Proxy Pattern

It provides the protection to the original object from the outside world.
Usage of Proxy Pattern:

It is used:
 It can be used in Virtual Proxy scenario---Consider a situation where
there is multiple database call to extract huge size image. Since this is
an expensive operation so here we can use the proxy pattern which
would create multiple proxies and point to the huge size memory
consuming object for further processing. The real object gets created
only when a client first requests/accesses the object and after that we
can just refer to the proxy to reuse the object. This avoids duplication
of the object and hence saving memory.
 It can be used in Protective Proxy scenario---It acts as an
authorization layer to verify that whether the actual user has access
the appropriate content or not. For example, a proxy server which
provides restriction on internet access in office. Only the websites
and contents which are valid will be allowed and the remaining ones
will be blocked
 It can be used in Remote Proxy scenario ---A remote proxy can be
thought about the stub in the RPC call. The remote proxy provides a
local representation of the object which is present in the different
address location. Another example can be providing interface for
remote resources such as web service or REST resources.
 It can be used in Smart Proxy scenario---A smart proxy provides
additional layer of security by interposing specific actions when the
object is accessed. For example, to check whether the real object is
locked or not before accessing it so that no other objects can change it.
Example of Proxy Pattern

Let's understand the example of proxy design pattern by the below UML
diagram.

UML for Proxy Pattern:


Implementation of above UML:
Step 1 Create an OfficeInternetAccess interface.
public interface OfficeInternetAccess {
public void grantInternetAccess();
}
Step 2

Create a RealInternetAccess class that will


implement OfficeInternetAccess interface for granting the permission to
the specific employee.
File: RealInternetAccess.java

public class RealInternetAccess implements OfficeInternetAccess {


private String employeeName;
public RealInternetAccess(String empName) {
this.employeeName = empName;
}
@Override
public void grantInternetAccess() {
System.out.println("Internet Access granted for employee: "+ employee
Name);
} }
Step 3
Create a proxyInternetaccess class that will implment officeInternetAccess
interface for providing the object of RealInternetAccess class.
File: ProxyInternetAccess.java

public class ProxyInternetAccess implements OfficeInternetAccess {


private String employeeName;
private RealInternetAccess realaccess;
public ProxyInternetAccess(String employeeName) {
this.employeeName = employeeName;
}
@Override
public void grantInternetAccess()
{ if (getRole(employeeName) > 4)
{
realaccess = new RealInternetAccess(employeeName);
realaccess.grantInternetAccess();
}
else
{
System.out.println("No Internet access granted. Your job level is below 5");
}
}
public int getRole(String emplName) {
// Check role from the database based on Name and designation

// return job level or job designation.


return 9;
}
}
Step 4

Now, Create a ProxyPatternClient class that can access the internet actually.
File: ProxyPatternClient.java
public class ProxyPatternClient {
public static void main(String[] args)
{
OfficeInternetAccess access = new ProxyInternetAccess("Ashwani Rajput");
access.grantInternetAccess();
} }
Output

No Internet access granted. Your job level is below 5

1.1.8 DECORATOR PATTERN


A Decorator Pattern says that just "attach a flexible additional
responsibilities to an object dynamically".In other words, The Decorator
Pattern uses composition instead of inheritance to extend the functionality of
an object at runtime.The Decorator Pattern is also known as Wrapper.
Advantage of Decorator Pattern

 It provides greater flexibility than static inheritance.

 It enhances the extensibility of the object, because changes are made


by coding new classes.

 It simplifies the coding by allowing you to develop a series of


functionality from targeted classes instead of coding all of the behavior
into the object.
Usage of Decorator Pattern

It is used:

 When you want to transparently and dynamically add responsibilities


to objects without affecting other objects.

 When you want to add responsibilities to an object that you may want
to change in future.

 Extending functionality by sub-classing is no longer practical.


Step 1 : Create a Food interface.
public interface Food {
public String prepareFood();
public double foodPrice();

}// End of the Food interface


UML for Decorator Pattern:

Create a VegFood class that will implements the Food interface and override
its all methods.
File: VegFood.java
public class VegFood implements Food {
public String prepareFood(){
return "Veg Food";
}
public double foodPrice(){
return 50.0;
}
}
Step 3:Create a FoodDecorator abstract class that will implements the Food
interface and override it's all methods and it has the ability to decorate some
more foods.
File: FoodDecorator.java
public abstract class FoodDecorator implements Food{
private Food newFood;
public FoodDecorator(Food newFood) {
this.newFood=newFood;
}
@Override
public String prepareFood(){
return newFood.prepareFood();
}
public double foodPrice(){
return newFood.foodPrice();
}
}
Step 4:Create a NonVegFood concrete class that will extend the
FoodDecorator class and override it's all methods.
File: NonVegFood.java

public class NonVegFood extends FoodDecorator{


public NonVegFood(Food newFood) {
super(newFood);
}
public String prepareFood(){
return super.prepareFood() +" With Roasted Chiken and Chiken Curry
";
}
public double foodPrice() {
return super.foodPrice()+150.0;
}
}
Step 5:Create a ChineeseFood concrete class that will extend the
FoodDecorator class and override it's all methods.
File: ChineeseFood.java
public class ChineeseFood extends FoodDecorator{
public ChineeseFood(Food newFood) {
super(newFood);
}
public String prepareFood(){
return super.prepareFood() +" With Fried Rice and Manchurian ";
}
public double foodPrice() {
return super.foodPrice()+65.0;
} }
Step 6:Create a DecoratorPatternCustomer class that will use Food interface
to use which type of food customer wants means (Decorates).
File: DecoratorPatternCustomer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DecoratorPatternCustomer {
private static int choice;
public static void main(String args[]) throws NumberFormatException,
IOException {
do{
System.out.print("========= Food Menu ============ \n");
System.out.print(" 1. Vegetarian Food. \n");
System.out.print(" 2. Non-Vegetarian Food.\n");
System.out.print(" 3. Chineese Food. \n");
System.out.print(" 4. Exit \n");
System.out.print("Enter your choice: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
choice=Integer.parseInt(br.readLine());
switch (choice) {
case 1:{
VegFood vf=new VegFood();
System.out.println(vf.prepareFood());
System.out.println( vf.foodPrice());
}
break;
case 2:{
Food f1=new NonVegFood((Food) new VegFood());
System.out.println(f1.prepareFood());
System.out.println( f1.foodPrice());
}
break;
case 3:{
Food f2=new ChineeseFood((Food) new VegFood());
System.out.println(f2.prepareFood());
System.out.println( f2.foodPrice());
}
break;
default:{
System.out.println("Other than these no food available");
}
return;
}//end of switch

}while(choice!=4);
} }
________________________________________
download this Decorator Pattern Example
Output
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 1
Veg Food
50.0
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 2
Veg Food With Roasted Chiken and Chiken Curry
200.0
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 3
Veg Food With Fried Rice and Manchurian
115.0
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 4
Other than these no food available
1.1.9 TEMPLATE PATTERN
A Template Pattern says that "just define the skeleton of a function in
an operation, deferring some steps to its subclasses".
Benefits:

It is very common technique for reusing the code.This is only the main
benefit of it.
Usage:

It is used when the common behavior among sub-classes should be


moved to a single common class by avoiding the duplication.
Implementation of Template Pattern:

Step 1:Create a Game abstract class.


//This is an abstract class.
public abstract class Game {
abstract void initialize();
abstract void start();
abstract void end();
public final void play(){
//initialize the game initialize();
//start game start( );
//end game end(); } }// End of the Game abstract class.
Step 2:
Create a Chess class that will extend Game abstract class for giving the
definition to its method.
//This is a class.
public class Chess extends Game {
@Override

void initialize() {
System.out.println("Chess Game Initialized! Start playing.");
}
@Override
void start() {
System.out.println("Game Started. Welcome to in the chess game!"
);
}
@Override
void end() {
System.out.println("Game Finished!");
}
}// End of the Chess class
Step 3:
Create a Soccer class that will extend Game abstract class for giving
the definition to its method.
//This is a class.
public class Soccer extends Game {
@Override
void initialize() {
System.out.println("Soccer Game Initialized! Start playing.");
}
@Override
void start() {
System.out.println("Game Started. Welcome to in the Soccer game!
");
}
@Override
void end() {
System.out.println("Game Finished!");
}
}// End of the Soccer class.
Step 4:
Create a TemplatePatternDemo class.
//This is a class.
public class TemplatePatternDemo {
public static void main(String[] args) throws InstantiationException, Illeg
alAccessException, ClassNotFoundException {
Class c=Class.forName(args[0]);
Game game=(Game) c.newInstance();
game.play();
}
}// End of the Soccer class

Output:
No Internet access granted. Your job level is below 5

1.1.10 COMMAND PATTERN


A Command Pattern says that "encapsulate a request under an object
as a command and pass it to invoker object. Invoker object looks for the
appropriate object which can handle this command and pass the command
to the corresponding object and that object executes the command".It is also
known as Action or Transaction.
Advantage of command pattern

 It separates the object that invokes the operation from the object that
actually performs the operation.
 It makes easy to add new commands, because existing classes remain
unchanged.

Usage of command pattern:

It is used:
 When you need parameterize objects according to an action perform.
 When you need to create and execute requests at different times.
 When you need to support rollback, logging or transaction
functionality.
UML for command pattern:
These are the following participants of the Command Design pattern:
 Command This is an interface for executing an operation.
 ConcreteCommand This class extends the Command interface and
implements the execute method. This class creates a binding between
the action and the receiver.
 Client This class creates the ConcreteCommand class and associates it
with the receiver.
 Invoker This class asks the command to carry out the request.
 Receiver This class knows to perform the operation.

Implementation of above UML:

Step 1:Create a ActionListernerCommand interface that will act as a


Command.

public interface ActionListenerCommand {


public void execute();
}
Step 2: Create a Document class that will act as a Receiver
.File: Document.java
public class Document {
public void open(){
System.out.println("Document Opened");
}
public void save(){
System.out.println("Document Saved");
}
}
Step 3

Create a ActionOpen class that will act as an ConcreteCommand.


File: ActionOpen.java

public class ActionOpen implements ActionListenerCommand{


private Document doc;
public ActionOpen(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.open();
}
}
Step 4

Create a ActionSave class that will act as an ConcreteCommand.File:


AdapterPatternDemo.java
public class ActionSave implements ActionListenerCommand{
private Document doc;
public ActionSave(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.save(); } }
Step 5

Create a MenuOptions class that will act as an Invoker.


File: ActionSave.java

public class ActionSave implements ActionListenerCommand{


private Document doc;
public ActionSave(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.save();
} }
Step 6

Create a CommanPatternClient class that will act as a Client.


File: AdapterPatternDemo.java

public class CommandPatternClient {


public static void main(String[] args) {
Document doc = new Document();
ActionListenerCommand clickOpen = new ActionOpen(doc);
ActionListenerCommand clickSave = new ActionSave(doc);
MenuOptions menu = new MenuOptions(clickOpen, clickSave);

menu.clickOpen();
menu.clickSave();
}}
Output
1. Document Opened
2. Document Saved
Mediator Pattern

A Mediator Pattern says that "to define an object that encapsulates


how a set of objects interact". Mediator pattern is used to reduce
communication complexity between multiple objects or classes. This pattern
provides a mediator class which normally handles all the communications
between different classes and supports easy maintainability of the code by
loose coupling.
Benefits:

 It decouples the number of classes.


 It simplifies object protocols.
 It centralizes the control.
 The individual components become simpler and much easier to deal
with because they don't need to pass messages to one another.
The components don't need to contain logic to deal with their
intercommunication and therefore, they are more generic.
Usage:

 It is commonly used in message-based systems likewise chat


applications.
 When the set of objects communicate in complex but in well-defined ways.

UML for Mediator Pattern


Participants:
 ApnaChatroom :- defines the interface for interacting with
participants.
 ApnaChatroomImpl :- implements the operations defined by the
Chatroom interface. The operations are managing the interactions
between the objects: when one participant sends a message, the
message is sent to the other participants.
 Participant :- defines an interface for the users involved in chatting.
User1, User2, ...UserN :- implements Participant interface; the
participant can be a number of users involved in chatting. But each
Participant will keep only a reference to the ApnaChatRoom
Implementation of Mediator Pattern:
Step 1:
Create a ApnaChatRoom interface.
//This is an interface.
public interface ApnaChatRoom {
public void showMsg(String msg, Participant p);
}// End of the ApnaChatRoom interface.
Step 2:Create a ApnaChatRoomIml class that will implement ApnaChatRoom
interface and will also use the number of participants involved in chatting
through Participant interface.
//This is a class.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ApnaChatRoomImpl implements ApnaChatRoom{
//get current date time

DateFormat dateFormat = new SimpleDateFormat("E dd-MM-yyyy hh:m


m a");
Date date = new Date();
@Override
public void showMsg(String msg, Participant p) {
System.out.println(p.getName()+"'gets message: "+msg);
System.out.println("\t\t\t\t"+"["+dateFormat.format(date).toString()
+"]");
}
}// End of the ApnaChatRoomImpl class.
Step 3:Create a Participant abstract class.
//This is an abstract class.
public abstract class Participant {
public abstract void sendMsg(String msg);
public abstract void setname(String name);
public abstract String getName();
}// End of the Participant abstract class.
Step 4:
Create a User1 class that will extend Participant abstract class and will
use the ApnaChatRoom interface.
//This is a class.
public class User1 extends Participant {
private String name;
private ApnaChatRoom chat;
@Override
public void sendMsg(String msg) {
chat.showMsg(msg,this);
}
@Override
public void setname(String name) {
this.name=name;
}
@Override
public String getName() {
return name;
}
public User1(ApnaChatRoom chat){
this.chat=chat;
}
}// End of the User1 class.
Step 5:Create a User2 class that will extend Participant abstract class
and will use the ApnaChatRoom interface.
//This is a class.
public class User2 extends Participant {
private String name;
private ApnaChatRoom chat;
@Override
public void sendMsg(String msg) {
this.chat.showMsg(msg,this);
}
@Override
public void setname(String name) {
this.name=name;
}
@Override
public String getName() {
return name;
}
public User2(ApnaChatRoom chat){
this.chat=chat;
}
}
// End of the User2 class.
Step 6:
Create a MediatorPatternDemo class that will use participants involved in
chatting.
//This is a class.
public class MediatorPatternDemo {
public static void main(String args[])
{
ApnaChatRoom chat = new ApnaChatRoomImpl();
User1 u1=new User1(chat);
u1.setname("Ashwani Rajput");
u1.sendMsg("Hi Ashwani! how are you?");
User2 u2=new User2(chat);
u2.setname("Soono Jaiswal");
u2.sendMsg("I am Fine ! You tell?");
}
}// End of the MediatorPatternDemo class.

Output:
1.2 COLLECTION FRAMEWORK
Collections in Java

The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.Java Collections can achieve all
the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion. Java Collection means a single unit of
objects. Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
What is Collection in Java?

A Collection represents a single unit of objects, i.e., a group.a Tr Catch

What is a framework in Java?

 It provides readymade architecture.


 It represents a set of classes and interfaces.
 It is optional.
What is Collection framework?

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:
 Interfaces and its implementations, i.e., classes
 Algorithm
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util
package contains all the classes and interfaces for the Collection framework.
Methods of Collection interface

There are many methods declared in the Collection interface. They are
as follows:
Method Description
public boolean add(E e) It is used to insert an element in this
collection.
publicboolean It is used to insert the specified collection
addAll(Collection<? elements in the invoking collection.
extends E> c)
public boolean It is used to delete an element from the
remove(Object collection.
element)
publicboolean It is used to delete all the elements of the
removeAll(Collection<? specified collection from the invoking
> c) collection.
default boolean It is used to delete all the elements of the
removeIf(Predicate<? collection that satisfy the specified
super E> filter) predicate.
publicboolean It is used to delete all the elements of
retainAll(Collection<?> invoking collection except the specified
c) collection.
public int size() It returns the total number of elements in
the collection.
public void clear() It removes the total number of elements
from the collection.
public boolean It is used to search an element.
contains(Object
element)
public boolean It is used to search the specified collection
containsAll(Collection<? in the collection.
> c)
public Iterator iterator() It returns an iterator.
public Object[] toArray() It converts collection into array.
public <T> T[] It converts collection into array. Here, the
toArray(T[] a) runtime type of the returned array is that
of the specified array.
public boolean It checks if collection is empty.
isEmpty()
default Stream<E> It returns a possibly parallel Stream with
parallelStream() the collection as its source.
default Stream<E> It returns a sequential Stream with the
stream() collection as its source.
default Spliterator<E> It generates a Spliterator over the
spliterator() specified elements in the collection.
public boolean It matches two collections.
equals(Object element)
public int hashCode() It returns the hash code number of the
collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in a
forward direction only.
Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
Method Description
public boolean It returns true if the iterator has more elements
hasNext() otherwise it returns false.
public Object next() It returns the element and moves the cursor pointer
to the next element.
public void It removes the last elements returned by the iterator.
remove() It is less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes.
The Collection interface extends the Iterable interface and therefore all the
subclasses of Collection interface also implement the Iterable interface.It
contains only one abstract method. i.e.,
Iterator<T> iterator()

It returns the iterator over the elements of type T.


Collection Interface

The Collection interface is the interface which is implemented by all


the classes in the collection framework. It declares the methods that every
collection will have. In other words, we can say that the Collection interface
builds the foundation on which the collection framework depends.Some of
the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the
subclasses of Collection interface.
List Interface

List interface is the child interface of Collection interface. It inhibits a


list type data structure in which we can store the ordered collection of
objects. It can have duplicate values.List interface is implemented by the
classes ArrayList, LinkedList, Vector, and Stack.To instantiate the List
interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array
to store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored
in the ArrayList class can be randomly accessed. Consider the following
example.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}} }
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList

LinkedList implements the Collection interface. It uses a doubly linked


list internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.
Consider the following example.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} }}
Output:
Ravi
Vijay
Ravi
Ajay
Vector

Vector uses a dynamic array to store the data elements. It is similar to


ArrayList. However, It is synchronized and contains many methods that are
not the part of Collection framework.Consider the following example.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ayush
Amit
Ashish
Garima
Stack

The stack is the subclass of Vector. It implements the last-in-first-out


data structure, i.e., Stack. The stack contains all of the methods of Vector
class and also provides its methods like boolean push(), boolean peek(),
boolean push(object o), which defines its properties.
Consider the following example.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined


as an ordered list that is used to hold the elements which are about to be
processed. There are various classes like PriorityQueue, Deque, and
ArrayDeque which implements the Queue interface.Queue interface can be
instantiated as:
Queue<String> q1 = new PriorityQueue();
Queue<String> q2 = new ArrayDeque();
PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the


elements or objects which are to be processed by their priorities.
PriorityQueue doesn't allow null values to be stored in the queue.Consider
the following example.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
} } }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Deque Interface

Deque interface extends the Queue interface. In Deque, we can


remove and add the elements from both the side. Deque stands for a double-
ended queue which enables us to perform the operations at both the
ends.Deque can be instantiated as:
Deque d = new ArrayDeque();

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to


use the Deque. Unlike queue, we can add or delete the elements from both
the ends.ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.
Consider the following example.
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
} }}
Output:
Gautam
Karan
Ajay

Set Interface

Set Interface in Java is present in java.util package. It extends the


Collection interface. It represents the unordered set of elements which
doesn't allow us to store the duplicate items. We can store at most one null
value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet

HashSet class implements Set Interface. It represents the collection


that uses a hash table for storage. Hashing is used to store the elements in
the HashSet. It contains unique items.
Consider the following example.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Vijay
Ravi
Ajay
LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set


Interface. It extends the HashSet class and implements Set interface. Like
HashSet, It also contains unique elements. It maintains the insertion order
and permits null elements.Consider the following example.
import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ravi
Vijay
Ajay
SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering


on its elements. The elements of the SortedSet are arranged in the
increasing (ascending) order. The SortedSet provides the additional methods
that inhibit the natural ordering of the elements.The SortedSet can be
instantiated as:
SortedSet<data-type> set = new TreeSet();

TreeSet

Java TreeSet class implements the Set interface that uses a tree for
storage. Like HashSet, TreeSet also contains unique elements. However, the
access and retrieval time of TreeSet is quite fast. The elements in TreeSet
stored in ascending order.Consider the following example:
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ajay
Ravi
Vijay

1.3 ARRAYLIST CLASS

Java ArrayList class uses a dynamic array for storing the elements. It is
like an array, but there is no size limit. We can add or remove elements
anytime. So, it is much more flexible than the traditional array. It is found in
the java.util package. It is like the Vector in C++.The ArrayList in Java can
have the duplicate elements also. It implements the List interface so we can
use all the methods of List interface here. The ArrayList maintains the insertion
order internally.It inherits the AbstractList class and implements List
interface.The important points about Java ArrayList class are:
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index
basis.
 In ArrayList, manipulation is little bit slower than the LinkedList in Java
because a lot of shifting needs to occur if any element is removed from
the array list.
Hierarchy of ArrayList class

Java ArrayList class extends AbstractList class which implements List


interface. The List interface extends the Collection and Iterable interfaces in
hierarchical order.
ArrayList class declaration

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


 public class ArrayList<E> extends AbstractList<E> implements List<E
>, RandomAccess, Cloneable, Serializable
 public class ArrayList extends AbstractList implements List,
RandomAccess, Cloneable, Serializable
Constructors of ArrayList

Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection<? It is used to build an array list that is
extends E> c) initialized with the elements of the collection
c.
ArrayList(int capacity) It is used to build an array list that has the
specified initial capacity.
Methods of ArrayList
void add(int index, E element) It is used to insert the specified
element at the specified position in a
list.
boolean add(E e) It is used to append the specified
element at the end of a list.
boolean addAll(Collection<? It is used to append all of the elements
extends E> c) in the specified collection to the end of
this list, in the order that they are
returned by the specified collection's
iterator.
boolean addAll(int index, It is used to append all the elements in
Collection<? extends E> c) the specified collection, starting at the
specified position of the list.
void clear() It is used to remove all of the elements
from this list.
void ensureCapacity(int It is used to enhance the capacity of
requiredCapacity) an ArrayList instance.
E get(int index) It is used to fetch the element from the
particular position of the list.
boolean isEmpty() It returns true if the list is empty,
otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list
of the last occurrence of the specified
element, or -1 if the list does not
contain this element.
Object[] toArray() It is used to return an array containing
all of the elements in this list in the
correct order.
<T> T[] toArray(T[] a) It is used to return an array containing
all of the elements in this list in the
correct order.
Object clone() It is used to return a shallow copy of
an ArrayList.
boolean contains(Object o) It returns true if the list contains the
specified element
int indexOf(Object o) It is used to return the index in this list
of the first occurrence of the specified
element, or -1 if the List does not
contain this element.
E remove(int index) It is used to remove the element
present at the specified position in the
list.
boolean remove(Object o) It is used to remove the first
occurrence of the specified element.
boolean removeAll(Collection<?> It is used to remove all the elements
c) from the list.
boolean removeIf(Predicate<? It is used to remove all the elements
super E> filter) from the list that satisfies the given
predicate.
protected void removeRange(int It is used to remove all the elements
fromIndex, int toIndex) lies within the given range.
void It is used to replace all the elements
replaceAll(UnaryOperator<E> from the list with the specified
operator) element.
void retainAll(Collection<?> c) It is used to retain all the elements in
the list that are present in the
specified collection.
E set(int index, E element) It is used to replace the specified
element in the list, present at the
specified position.
void sort(Comparator<? super E> It is used to sort the elements of the
c) list on the basis of specified
comparator.
Spliterator<E> spliterator() It is used to create spliterator over the
elements in a list.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies
toIndex) within the given range.
int size() It is used to return the number of
elements present in the list.
void trimToSize() It is used to trim the capacity of this
ArrayList instance to be the list's
current size.

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it
is generic.Java new generic collection allows you to have only one type of
object in a collection. Now it is type safe so typecasting is not required at
runtime.Let's see the old non-generic example of creating java collection.
 ArrayList list=new ArrayList();
 ArrayList list=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
ArrayList<String> list=new ArrayList<String>();
ArrayList list=new ArrayList();//creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now
ArrayList is forced to have the only specified type of objects in it. If you try to
add another type of object, it gives compile time error.
Java ArrayList Example

import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
System.out.println(list);
} }
output
[Mango, Apple, Banana, Grapes]
Iterating ArrayList using Iterator

Let's see an example to traverse ArrayList elements using the Iterator


interface.
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Mango

Apple
Banana
Grapes
Get and Set ArrayList
The get() method returns the element at the specified index, whereas
the set() method changes the element.
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
System.out.println("Returning element: "+al.get(1));
al.set(1,"Dates");
for(String fruit:al)
System.out.println(fruit);
}}
Output:

Returning element: Apple

Mango
Dates
Banana
Grapes
How to Sort ArrayList

The java.util package provides a utility class Collections which has the
static method sort(). Using the Collections.sort() method, we can easily
sort the ArrayList.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
Collections.sort(list1);
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
Collections.sort(list2);
for(Integer number:list2)
System.out.println(number);
} }
Output:

Apple

Banana

Grapes
Mango
Sorting numbers...
1
11
21
51
Ways to iterate the elements of the collection in Java

There are various ways to traverse the collection elements:


 By Iterator interface.
 By for-each loop.
 By ListIterator interface.
 By for loop.
 By forEach() method.
 By forEachRemaining() method.

Iterating Collection through remaining ways

Let's see an example to traverse the ArrayList elements through other


ways
import java.util.*;
class ArrayList4 {
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
System.out.println("Traversing list through List Iterator:");
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious()) {
String str=list1.previous();
System.out.println(str);
}
System.out.println("Traversing list through for loop:");
for(int i=0;i<list.size();i++)
{ System.out.println(list.get(i)); }

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


;
list.forEach(a->
{ System.out.println(a);
});
System.out.println("Traversing list through forEachRemaining() me
thod:"); Iterator<String> itr=list.iterator();
itr.forEachRemaining(a->
{ System.out.println(a);
}); } }
Output:

Traversing list through List Iterator:


Ajay
Ravi
Vijay
Ravi
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay
1.4 LINKEDLIST CLASS

Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the AbstractList class and
implements List and Deque interfaces.
The important points about Java LinkedList are:

 Java LinkedList class can contain duplicate elements.

 Java LinkedList class maintains insertion order.

 Java LinkedList class is non synchronized.

 In Java LinkedList class, manipulation is fast because no shifting needs


to occur.

 Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class

Java LinkedList class extends AbstractSequentialList class and


implements List and Deque interfaces.
Doubly Linked List

In the case of a doubly linked list, we can add or remove elements


from both sides.
LinkedList class declaration

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


public class LinkedList<E> extends AbstractSequentialList<E> implem
ents List<E>, Deque<E>, Cloneable, Serializable
Constructors of Java LinkedList

LinkedList():It is used to construct an empty list.


Syntax: LinkedList(Collection<? extends E> c)
It is used to construct a list containing the elements of the specified
collection, in the order, they are returned by the collection's iterator.
Method

boolean add(E e):


 It is used to append the specified element to the end of a list.
 void add(int index, E element)
 It is used to insert the specified element at the specified position index
in a list.
boolean addAll(Collection<? extends E> c)
 It is used to append all of the elements in the specified collection to
the end of this list, in the order that they are returned by the specified
collection's iterator.
 boolean addAll(Collection<? extends E> c)
 It is used to append all of the elements in the specified collection to
the end of this list, in the order that they are returned by the specified
collection's iterator.
boolean addAll(int index, Collection<? extends E> c)
 It is used to append all the elements in the specified collection, starting
at the specified position of the list.
 void addFirst(E e)
 It is used to insert the given element at the beginning of a list.
void addLast(E e):It is used to append the given element to the end of a
list.
void clear():It is used to remove all the elements from a list.
Object clone():It is used to return a shallow copy of an ArrayList.
boolean contains(Object o):It is used to return true if a list contains a
specified element.
Iterator<E> descendingIterator():It is used to return an iterator over the
elements in a deque in reverse sequential order.
E element():It is used to retrieve the first element of a list.
E get(int index):It is used to return the element at the specified position in
a list.
E getFirst():It is used to return the first element in a list.
E getLast():It is used to return the last element in a list.
int indexOf(Object o):It is used to return the index in a list of the first
occurrence of the specified element, or -1 if the list does not contain any
element.
int lastIndexOf(Object o):It is used to return the index in a list of the last
occurrence of the specified element, or -1 if the list does not contain any
element.
ListIterator<E> listIterator(int index):It is used to return a list-iterator of
the elements in proper sequence, starting at the specified position in the list.
boolean offer(E e):It adds the specified element as the last element of a
list.
boolean offerFirst(E e):It inserts the specified element at the front of a
list.
boolean offerLast(E e):It inserts the specified element at the end of a list.
E peek():It retrieves the first element of a list

E peekFirst():It retrieves the first element of a list or returns null if a list is


empty.
E peekLast():It retrieves the last element of a list or returns null if a list is
empty.
E poll():It retrieves and removes the first element of a list.
E pollFirst():It retrieves and removes the first element of a list, or returns
null if a list is empty.
E pollLast():It retrieves and removes the last element of a list, or returns
null if a list is empty.
E pop():It pops an element from the stack represented by a list.
void push(E e):It pushes an element onto the stack represented by a list.
E remove():It is used to retrieve and removes the first element of a list.
E remove(int index):It is used to remove the element at the specified
position in a list.
boolean remove(Object o):It is used to remove the first occurrence of the
specified element in a list.
E removeFirst():It removes and returns the first element from a list.
boolean removeFirstOccurrence(Object o):It is used to remove the first
occurrence of the specified element in a list (when traversing the list from
head to tail).
E removeLast():It removes and returns the last element from a list.
boolean removeLastOccurrence(Object o):It removes the last
occurrence of the specified element in a list (when traversing the list from
head to tail).
E set(int index, E element):It replaces the element at the specified
position in a list with the specified element.
Object[] toArray():It is used to return an array containing all the elements
in a list in proper sequence (from first to the last element).eg:<T> T[ ] to
Array (T[] a).It returns an array containing all the elements in the proper
sequence (from first to the last element); the runtime type of the returned
array is that of the specified array.
int size():It is used to return the number of elements in a list.
Java LinkedList Example

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

Vijay
Ravi
Ajay
1.5 ARRAYLIST VS. LINKEDLIST
ArrayList and LinkedList both implements List interface and maintains
insertion order. Both are non synchronized classes.However, there are many
differences between ArrayList and LinkedList classes that are given below.
ArrayList LinkedList
1) ArrayList internally uses a dynamic LinkedList internally uses
array to store the elements. a doubly linked list to
store the elements.
2) Manipulation with ArrayList Manipulation with LinkedList
is slow because it internally uses an array. is faster than ArrayList
If any element is removed from the array, because it uses a doubly
all the bits are shifted in memory. linked list, so no bit shifting
is required in memory.
3) An ArrayList class can act as a list only LinkedList class can act as a
because it implements List only. list and queue both
because it implements List
and Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.

Example of ArrayList and LinkedList in Java

.import java.util.*;
class TestArrayLinked{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
List<String> al2=new LinkedList<String>();//creating linkedlist
al2.add("James");//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
} }
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
1.6 LISTITERATOR INTERFACE
ListIterator Interface is used to traverse the element in a backward and
forward direction.
ListIterator Interface declaration
public interface ListIterator<E> extends Iterator<E>
Methods of Java ListIterator Interface:
Method Description
void add(E e) This method inserts the specified element into the
list.
boolean hasNext() This method returns true if the list iterator has more
elements while traversing the list in the forward
direction.
E next() This method returns the next element in the list and
advances the cursor position.

int nextIndex() This method returns the index of the element that
would be returned by a subsequent call to next()
boolean This method returns true if this list iterator has more
hasPrevious() elements while traversing the list in the reverse
direction.
E previous() This method returns the previous element in the list
and moves the cursor position backward.
E previousIndex() This method returns the index of the element that
would be returned by a subsequent call to previous().
void remove() This method removes the last element from the list
that was returned by next() or previous() methods
void set(E e) This method replaces the last element returned by
next() or previous() methods with the specified
element.
Example of ListIterator Interface
import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:
"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
} }
Output:
Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit
1.7 HASHSET CLASS

Java HashSet class is used to create a collection that uses a hash table
for storage. It inherits the AbstractSet class and implements Set
interface.The important points about Java HashSet class are:
 HashSet stores the elements by using a mechanism called hashing.
 HashSet contains unique elements only.
 HashSet allows null value.
 HashSet class is non synchronized.
 HashSet doesn't maintain the insertion order. Here, elements are
inserted on the basis of their hashcode.
 HashSet is the best approach for search operations.
 The initial default capacity of HashSet is 16, and the load factor is 0.75.
Difference between List and Set

A list can contain duplicate elements whereas Set contains unique


elements only.
Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set


interface. The Set interface inherits Collection and Iterable interfaces in
hierarchical order.
HashSet class declaration
Let's see the declaration for java.util.HashSet class.
public class HashSet<E> extends AbstractSet<E> implements Set<E
>, Cloneable, Serializable
Constructors of Java HashSet class

Constructor Description
HashSet() It is used to construct a default
HashSet.
HashSet(int capacity) It is used to initialize the
capacity of the hash set to the
given integer value capacity.
The capacity grows
automatically as elements are
added to the HashSet.
HashSet(int capacity, float loadFactor) It is used to initialize the
capacity of the hash set to the
given integer value capacity
and the specified load factor.
HashSet(Collection<? extends E> c) It is used to initialize the hash
set by using the elements of
the collection c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:
Modifier & Type Method Description
Boolean add(E e) It is used to add the
specified element to
this set if it is not
already present.
Void clear() It is used to remove all
of the elements from
the set.
Object clone() It is used to return a
shallow copy of this
HashSet instance: the
elements themselves
are not cloned.
Boolean contains(Object o) It is used to return true
if this set contains the
specified element.
Boolean isEmpty() It is used to return true
if this set contains no
elements.
Iterator<E> iterator() It is used to return an
iterator over the
elements in this set.
Boolean remove(Object o) It is used to remove
the specified element
from this set if it is
present.
Int size() It is used to return the
number of elements in
the set.
Spliterator<E> spliterator() It is used to create a
late-binding and fail-
fast Spliterator over
the elements in the
set.

Let's see a HashSet example where we are adding books to set and
printing all the books.
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quant
ity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouz
an","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "
+b.quantity);
} } }
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

1.8 LINKED HASHSET CLASS


Java LinkedHashSet class is a Hashtable and Linked list implementation
of the set interface. It inherits HashSet class and implements Set
interface.The important points about Java LinkedHashSet class are:

 Java LinkedHashSet class contains unique elements only like HashSet.


 Java LinkedHashSet class provides all optional set operation and
permits null elements.
 Java LinkedHashSet class is non synchronized.
 Java LinkedHashSet class maintains insertion order.
Hierarchy of LinkedHashSet class

The LinkedHashSet class extends HashSet class which implements Set


interface. The Set interface inherits Collection and Iterable interfaces in
hierarchical order.
LinkedHashSet class declaration

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


public class LinkedHashSet<E> extends HashSet<E> implements Set
<E>, Cloneable, Serializable
Constructors of Java LinkedHashSet class

Constructor Description
HashSet() It is used to construct a default
HashSet.
HashSet(Collection c) It is used to initialize the hash set by
using the elements of the collection
c.
LinkedHashSet(int capacity) It is used initialize the capacity of the
linked hash set to the given integer
value capacity.
LinkedHashSet(int capacity, float It is used to initialize both the
fillRatio) capacity and the fill ratio (also called
load capacity) of the hash set from
its argument.
Java LinkedHashSet Example: Book
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quant
ity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouz
an","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
//Traversing hash table
for(Book b:hs){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "
+b.quantity);
} } }
Output:
101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications & Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

1.9 TREESET CLASS

Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements the NavigableSet
interface. The objects of the TreeSet class are stored in ascending order.The
important points about Java TreeSet class are:

 Java TreeSet class contains unique elements only like HashSet.


 Java TreeSet class access and retrieval times are quiet fast.

 Java TreeSet class doesn't allow null element.

 Java TreeSet class is non synchronized.

 Java TreeSet class maintains ascending order.


Hierarchy of TreeSet class

Java TreeSet class implements the NavigableSet interface. The


NavigableSet interface extends SortedSet, Set, Collection and Iterable
interfaces in hierarchical order.
TreeSet class declaration

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


public class TreeSet<E> extends AbstractSet<E> implements Naviga
bleSet<E>, Cloneable, Serializable

Constructors of Java TreeSet class

Constructor Description
It is used to construct an empty tree set
that will be sorted in ascending order
TreeSet()
according to the natural order of the tree
set.
TreeSet(Collection<? extends It is used to build a new tree set that
E> c) contains the elements of the collection c.
It is used to construct an empty tree set
TreeSet(Comparator<? super
that will be sorted according to given
E> comparator)
comparator.
It is used to build a TreeSet that contains
TreeSet(SortedSet<E> s)
the elements of the given SortedSet.
Methods of Java TreeSet class

Method Description
boolean add(E e) It is used to add the specified
element to this set if it is not
already present.
boolean addAll(Collection<? extends E> It is used to add all of the
c) elements in the specified
collection to this set.
E ceiling(E e) It returns the equal or closest
greatest element of the
specified element from the set,
or null there is no such
element.
Comparator<? super E> comparator() It returns comparator that
arranged elements in order.
Iterator descendingIterator() It is used iterate the elements
in descending order.
NavigableSet descendingSet() It returns the elements in
reverse order.
E floor(E e) It returns the equal or closest
least element of the specified
element from the set, or null
there is no such element.
SortedSet headSet(E toElement) It returns the group of elements
that are less than the specified
element.
NavigableSet headSet(E toElement, It returns the group of elements
boolean inclusive) that are less than or equal to(if,
inclusive is true) the specified
element.
E higher(E e) It returns the closest greatest
element of the specified
element from the set, or null
there is no such element.
Iterator iterator() It is used to iterate the
elements in ascending order.
E lower(E e) It returns the closest least
element of the specified
element from the set, or null
there is no such element.
E pollFirst() It is used to retrieve and
remove the lowest(first)
element.
E pollLast() It is used to retrieve and
remove the highest(last)
element.
Spliterator spliterator() It is used to create a late-
binding and fail-fast spliterator
over the elements.
NavigableSet subSet(E fromElement, It returns a set of elements that
boolean fromInclusive, E toElement, lie between the given range.
boolean toInclusive)
SortedSet subSet(E fromElement, E It returns a set of elements that
toElement)) lie between the given range
which includes fromElement
and excludes toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that
are greater than or equal to the
specified element.
NavigableSet tailSet(E fromElement, It returns a set of elements that
boolean inclusive) are greater than or equal to (if,
inclusive is true) the specified
element.
boolean contains(Object o) It returns true if this set
contains the specified element.
boolean isEmpty() It returns true if this set
contains no elements.
boolean remove(Object o) It is used to remove the
specified element from this set
if it is present.
void clear() It is used to remove all of the
elements from this set.
Object clone() It returns a shallow copy of this
TreeSet instance.
E first() It returns the first (lowest)
element currently in this sorted
set.
E last() It returns the last (highest)
element currently in this sorted
set.
int size() It returns the number of
elements in this set.
Java TreeSet Example: Book
Let's see a TreeSet example where we are adding books to set and
printing all the books. The elements in TreeSet must be of a Comparable
type. String and Wrapper classes are Comparable by default. To add user-
defined objects in TreeSet, you need to implement the Comparable interface.
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quant
ity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){

return -1;
}else{

return 0;
}
}
}
public class TreeSetExample {
public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouz
an","Mc Graw Hill",4);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "
+b.quantity);
} } }
Output:
101 Data Communications & Networking Forouzan Mc Graw Hill 4

121 Let us C Yashwant Kanetkar BPB 8


233 Operating System Galvin Wiley 6
1.10 PRIORITYQUEUE CLASS
The PriorityQueue class provides the facility of using queue. But it does
not orders the elements in FIFO manner. It inherits AbstractQueue class.
PriorityQueue class declaration
Let's see the declaration for java.util.PriorityQueue class.
public class PriorityQueue<E> extends AbstractQueue<E> implement
s Serializable
Java PriorityQueue Example
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:head:Amit

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

1.11 MAP INTERFACE


A map contains values on the basis of key, i.e. key and value pair. Each
key and value pair is known as an entry. A Map contains unique keys.A Map
is useful if you have to search, update or delete elements on the basis of a
key.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and
SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap. The
hierarchy of Java Map is given below:

A Map doesn't allow duplicate keys, but you can have duplicate values.
HashMap and LinkedHashMap allow null keys and values, but TreeMap
doesn't allow any null key or value.A Map can't be traversed, so you need to
convert it into Set using keySet() or entrySet() method.
Class Description
HashMap HashMap is the implementation of Map,
but it doesn't maintain any order.
LinkedHashMap LinkedHashMap is the implementation of
Map. It inherits HashMap class. It maintains
insertion order.
TreeMap TreeMap is the implementation of Map and
SortedMap. It maintains ascending order.
Useful methods of Map interface
Method Description
V put(Object key, Object value) It is used to insert an entry
in the map.
void putAll(Map map) It is used to insert the
specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified
value with the specified
key in the map only if it is
not already specified.
V remove(Object key) It is used to delete an
entry for the specified key.
boolean remove(Object key, Object value) It removes the specified
values with the associated
specified keys from the
map.
Set keySet() It returns the Set view
containing all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view
containing all the keys and
values.
void clear() It is used to reset the map.
V compute(K key, BiFunction<? super K,? It is used to compute a
super V,? extends V> remappingFunction) mapping for the specified
key and its current
mapped value (or null if
there is no current
mapping).
V computeIfAbsent(K key, Function<? super It is used to compute its
K,? extends V> mappingFunction) value using the given
mapping function, if the
specified key is not already
associated with a value (or
is mapped to null), and
enters it into this map
unless null.
V computeIfPresent(K key, BiFunction<? super It is used to compute a
K,? super V,? extends V> remappingFunction) new mapping given the
key and its current
mapped value if the value
for the specified key is
present and non-null.
boolean containsValue(Object value) This method returns true if
some value equal to the
value exists within the
map, else return false.
boolean containsKey(Object key) This method returns true if
some key equal to the key
exists within the map, else
return false.
boolean equals(Object o) It is used to compare the
specified Object with the
Map.
void forEach(BiConsumer<? super K,? super It performs the given
V> action) action for each entry in the
map until all entries have
been processed or the
action throws an
exception.
V get(Object key) This method returns the
object that contains the
value associated with the
key.
V getOrDefault(Object key, V defaultValue) It returns the value to
which the specified key is
mapped, or defaultValue if
the map contains no
mapping for the key.
int hashCode() It returns the hash code
value for the Map
boolean isEmpty() This method returns true if
the map is empty; returns
false if it contains at least
one key.
V merge(K key, V value, BiFunction<? super If the specified key is not
V,? super V,? extends V> remappingFunction) already associated with a
value or is associated with
null, associates it with the
given non-null value.
V replace(K key, V value) It replaces the specified
value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value
newValue) with the new value for a
specified key.
void replaceAll(BiFunction<? super K,? super It replaces each entry's
V,? extends V> function) value with the result of
invoking the given function
on that entry until all
entries have been
processed or the function
throws an exception.
Collection values() It returns a collection view
of the values contained in
the map.
int size() This method returns the
number of entries in the
map.
MapEntry Interface
Entry is the subinterface of Map. So we will be accessed it by
Map.Entry name. It returns a collection-view of the map, whose elements are
of this class. It provides methods to get key and value.
Methods of Map.Entry interface

Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value
corresponding to this entry with the
specified value.
boolean equals(Object o) It is used to compare the specified
object with the other existing objects.
static <K extends It returns a comparator that compare
Comparable<? super K>,V> the objects in natural order on key.
Comparator<Map.Entry<K,V>>
comparingByKey()
static <K,V> It returns a comparator that compare
Comparator<Map.Entry<K,V>> the objects by key using the given
comparingByKey(Comparator<? Comparator.
super K> cmp)
static <K,V extends It returns a comparator that compare
Comparable<? superV>> the objects in natural order on value.
Comparator<Map.Entry<K,V>>
comparingByValue()
static<K,V> It returns a comparator that compare
Comparator<Map.Entry<K,V>> the objects by value using the given
comparingByValue(Comparator< Comparator.
? super V> cmp)
Java Map Example: Non-Generic (Old Style)
//Non-generic
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
} } }
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
Java Map Example: Generic (New Style)
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} } }
Output:
102 Rahul
100 Amit
101 Vijay
1.12 HASHMAP
Hashing

It is the process of converting an object into an integer value. The


integer value helps in indexing and faster searches.
HashMap

HashMap is a part of the Java collection framework. It uses a technique


called Hashing. It implements the map interface. It stores the data in the pair
of Key and Value. HashMap contains an array of the nodes, and the node is
represented as a class. It uses an array and LinkedList data structure
internally for storing Key and Value. There are four fields in HashMap.

Before understanding the internal working of HashMap, you must be


aware of hashCode() and equals() method.

o equals(): It checks the equality of two objects. It compares the Key,


whether they are equal or not. It is a method of the Object class. It can
be overridden. If you override the equals() method, then it is
mandatory to override the hashCode() method.
o hashCode(): This is the method of the object class. It returns the
memory reference of the object in integer form. The value received
from the method is used as the bucket number. The bucket number is
the address of the element inside the map. Hash code of null Key is 0.
o Buckets: Array of the node is called buckets. Each node has a data
structure like a LinkedList. More than one node can share the same
bucket. It may be different in capacity.

Insert Key, Value pair in HashMap

We use put() method to insert the Key and Value pair in the HashMap.
The default size of HashMap is 16 (0 to 15).
Example

In the following example, we want to insert three (Key, Value) pair in the
HashMap.
HashMap<String, Integer> map = new HashMap<>();
map.put("Aman", 19);
map.put("Sunny", 29);
map.put("Ritesh", 39);
Let's see at which index the Key, value pair will be saved into
HashMap. When we call the put() method, then it calculates the hash code
of the Key "Aman." Suppose the hash code of "Aman" is 2657860. To
store the Key in memory, we have to calculate the index.
Calculating Index
Index minimizes the size of the array. The Formula for calculating the
index is:
Index = hashcode(Key) & (n-1)
Where n is the size of the array. Hence the index value for "Aman" is:
Index = 2657860 & (16-1) = 4

The value 4 is the computed index value where the Key and value will
store in HashMap.

Hash Collision

This is the case when the calculated index value is the same for two or
more Keys. Let's calculate the hash code for another Key "Sunny."
Suppose the hash code for "Sunny" is 63281940. To store the Key in the
memory, we have to calculate index by using the index formula.
Index=63281940 & (16-1) = 4

The value 4 is the computed index value where the Key will be stored
in HashMap. In this case, equals() method check that both Keys are equal
or not. If Keys are same, replace the value with the current value.
Otherwise, connect this node object to the existing node object through
the LinkedList. Hence both Keys will be stored at index 4.
Similarly, we will store the Key "Ritesh." Suppose hash code for the Key
is 2349873. The index value will be 1. Hence this Key will be stored at
index 1.

get() method in HashMap


get() method is used to get the value by its Key. It will not fetch the
value if you don't know the Key. When get(K Key) method is called, it
calculates the hash code of the Key.Suppose we have to fetch the Key
"Aman." The following method will be called.
map.get(new Key("Aman"));
It generates the hash code as 2657860. Now calculate the index value
of 2657860 by using index formula. The index value will be 4, as we have
calculated above. get() method search for the index value 4. It compares
the first element Key with the given Key. If both keys are equal, then it
returns the value else check for the next element in the node if it exists.
In our scenario, it is found as the first element of the node and return the
value 19.Let's fetch another Key "Sunny."The hash code of the Key
"Sunny" is 63281940. The calculated index value of 63281940 is 4, as we
have calculated for put() method. Go to index 4 of the array and compare
the first element's Key with the given Key. It also compares Keys. In our
scenario, the given Key is the second element, and the next of the node is
null. It compares the second element Key with the specified Key and
returns the value 29. It returns null if the next of the node is null.
1.12 LINKEDHASHMAP CLASS
Java LinkedHashMap class is Hashtable and Linked list implementation
of the Map interface, with predictable iteration order. It inherits HashMap
class and implements the Map interface.
Points to remember
 Java LinkedHashMap contains values based on the key.
 Java LinkedHashMap contains unique elements.
 Java LinkedHashMap may have one null key and multiple null values.
 Java LinkedHashMap is non synchronized.
 Java LinkedHashMap maintains insertion order.
 The initial default capacity of Java HashMap class is 16 with a load
factor of 0.75.

LinkedHashMap class declaration

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


public class LinkedHashMap<K,V> extends HashMap<K,V> implemen
ts Map<K,V>

LinkedHashMap class Parameters

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


 K: It is the type of keys maintained by this map.
 V: It is the type of mapped values.
Constructors of Java LinkedHashMap class
Constructor Description
LinkedHashMap() It is used to construct a default
LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a
LinkedHashMap with the given
capacity.
LinkedHashMap(int capacity, float It is used to initialize both the
loadFactor) capacity and the load factor.
LinkedHashMap(int capacity, float It is used to initialize both the
loadFactor, boolean accessOrder) capacity and the load factor
with specified ordering mode.
LinkedHashMap(Map<? extends K,? It is used to initialize the
extends V> m) LinkedHashMap with the
elements from the given Map
class m.
Methods of Java LinkedHashMap class
Method Description
V get(Object key) It returns the value to which the
specified key is mapped.
void clear() It removes all the key-value pairs from
a map.
boolean containsValue(Object It returns true if the map maps one or
value) more keys to the specified value.
Set<Map.Entry<K,V>> entrySet() It returns a Set view of the mappings
contained in the map.
void forEach(BiConsumer<? super It performs the given action for each
K,? super V> action) entry in the map until all entries have
been processed or the action throws
an exception.
V getOrDefault(Object key, V It returns the value to which the
defaultValue) specified key is mapped or
defaultValue if this map contains no
mapping for the key.
Set<K> keySet() It returns a Set view of the keys
contained in the map
protected boolean It returns true on removing its eldest
removeEldestEntry(Map.Entry<K, entry.
V> eldest)
void replaceAll(BiFunction<? It replaces each entry's value with the
super K,? super V,? extends V> result of invoking the given function on
function) that entry until all entries have been
processed or the function throws an
exception.
Collection<V> values() It returns a Collection view of the
values contained in this map.
Java LinkedHashMap Example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,Str
ing>(); hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} } }
Output:100 Amit
101 Vijay
102 Rahul
1.13 TREEMAP CLASS

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


means of storing key-value pairs in sorted order.The important points about Java TreeMap
class are:
 Java TreeMap contains values based on the key. It implements the
NavigableMap interface and extends AbstractMap class.
 Java TreeMap contains only unique elements.
 Java TreeMap cannot have a null key but can have multiple null values.
 Java TreeMap is non synchronized.
 Java TreeMap maintains ascending order.
TreeMap class declaration

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


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

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


 K: It is the type of keys maintained by this map.
 V: It is the type of mapped values.Constructors of Java TreeMap class
Constructor Description
TreeMap() It is used to construct an empty
tree map that will be sorted
using the natural order of its key.
TreeMap(Comparator<? super K> It is used to construct an empty
comparator) tree-based map that will be
sorted using the comparator
comp.
TreeMap(Map<? extends K,? It is used to initialize a treemap
extends V> m) with the entries from m, which
will be sorted using the natural
order of the keys.
TreeMap(SortedMap<K,? extends It is used to initialize a treemap
V> m) with the entries from the
SortedMap sm, which will be
sorted in the same order as sm.

Methods of Java TreeMap class


Method Description
It returns the key-value pair
Map.Entry<K,V> ceilingEntry(K having the least key, greater than
key) or equal to the specified key, or
null if there is no such key.
It returns the least key, greater
K ceilingKey(K key) than the specified key or null if
there is no such key.
It removes all the key-value pairs
void clear()
from a map.
It returns a shallow copy of
Object clone()
TreeMap instance.
It returns the comparator that
Comparator<? super K>
arranges the key in order, or null if
comparator()
the map uses the natural ordering.
It returns a reverse order
NavigableSet<K>
NavigableSet view of the keys
descendingKeySet()
contained in the map.
NavigableMap<K,V> It returns the specified key-value
descendingMap() pairs in descending order.
It returns the key-value pair
Map.Entry firstEntry()
having the least key.
Map.Entry<K,V> floorEntry(K It returns the greatest key, less
key) than or equal to the specified key,
or null if there is no such key.
void forEach(BiConsumer<? It performs the given action for
super K,? super V> action) each entry in the map until all
entries have been processed or
the action throws an exception.
SortedMap<K,V> headMap(K It returns the key-value pairs
toKey) whose keys are strictly less than
toKey.
NavigableMap<K,V> headMap(K It returns the key-value pairs
toKey, boolean inclusive) whose keys are less than (or equal
to if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K It returns the least key strictly
key) greater than the given key, or null
if there is no such key.
K higherKey(K key) It is used to return true if this map
contains a mapping for the
specified key.
Set keySet() It returns the collection of keys
exist in the map.
Map.Entry<K,V> lastEntry() It returns the key-value pair
having the greatest key, or null if
there is no such key.
Map.Entry<K,V> lowerEntry(K It returns a key-value mapping
key) associated with the greatest key
strictly less than the given key, or
null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly
less than the given key, or null if
there is no such key.
NavigableSet<K> It returns a NavigableSet view of
navigableKeySet() the keys contained in this map.
Map.Entry<K,V> pollFirstEntry() It removes and returns a key-
value mapping associated with the
least key in this map, or null if the
map is empty.
Map.Entry<K,V> pollLastEntry() It removes and returns a key-
value mapping associated with the
greatest key in this map, or null if
the map is empty.
V put(K key, V value) It inserts the specified value with
the specified key in the map.
void putAll(Map<? extends K,? It is used to copy all the key-value
extends V> map) pair from one map to another
map.
V replace(K key, V value) It replaces the specified value for
a specified key.
boolean replace(K key, V It replaces the old value with the
oldValue, V newValue) new value for a specified key.
void replaceAll(BiFunction<? It replaces each entry's value with
super K,? super V,? extends V> the result of invoking the given
function) function on that entry until all
entries have been processed or
the function throws an exception.
NavigableMap<K,V> subMap(K It returns key-value pairs whose
fromKey, boolean fromInclusive, keys range from fromKey to
K toKey, boolean toInclusive) toKey.
SortedMap<K,V> subMap(K It returns key-value pairs whose
fromKey, K toKey) keys range from fromKey,
inclusive, to toKey, exclusive.
SortedMap<K,V> tailMap(K It returns key-value pairs whose
fromKey) keys are greater than or equal to
fromKey.
NavigableMap<K,V> tailMap(K It returns key-value pairs whose
fromKey, boolean inclusive) keys are greater than (or equal to,
if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains
a mapping for the specified key.
boolean containsValue(Object It returns true if the map maps
value) one or more keys to the specified
value.
K firstKey() It is used to return the first
(lowest) key currently in this
sorted map.
V get(Object key) It is used to return the value to
which the map maps the specified
key.
K lastKey() It is used to return the last
(highest) key currently in the
sorted map.
V remove(Object key) It removes the key-value pair of
the specified key from the map.
Set<Map.Entry<K,V>> It returns a set view of the
entrySet() mappings contained in the map.
int size() It returns the number of key-value
pairs exists in the hashtable.
Collection values() It returns a collection view of the
values contained in the map.

Java TreeMap Example


import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} } }
Output:
100 Amit

101 Vijay
102 Ravi
103 Rahul
1.14 COMPARABLE INTERFACE
Java Comparable interface is used to order the objects of the user-
defined class. This interface is found in java.lang package and contains only
one method named compareTo(Object). It provides a single sorting sequence
only, i.e., you can sort the elements on the basis of single data member only.
For example, it may be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): It is used to compare the current
object with the specified object. It returns
 positive integer, if the current object is greater than the specified
object.
 negative integer, if the current object is less than the specified object.
 zero, if the current object is equal to the specified object.
We can sort the elements of:
 String objects
 Wrapper class objects
 User-defined class objects
Collections class

Collections class provides static methods for sorting the elements of


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

Method of Collections class for sorting List elements

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

Let's see the example of the Comparable interface that sorts the list
elements on the basis of age.
File: Student.java
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
File: TestSort1.java

import java.util.*;
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
} } }
Output:
105 Jai 21
101 Vijay 23
106 Ajay 27
1.15 COMPARATOR INTERFACE
Java Comparator interface is used to order the objects of a user-
defined class.This interface is found in java.util package and contains 2
methods compare(Object obj1,Object obj2) and equals(Object element).It
provides multiple sorting sequences, i.e., you can sort the elements on the
basis of any data member, for example, rollno, name, age or anything else.
Methods of Java Comparator Interface

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

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

Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the


elements of List by the given Comparator.
Java Comparator Example (Non-generic Old Style)

Let's see the example of sorting the elements of List on the basis of
age and name. In this example, we have created 4 java classes:
 Student.java
 AgeComparator.java
 NameComparator.java
 Simple.java
 Student.java
This class contains three fields rollno, name and age and a parameterized
constructor.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){

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

This class defines comparison logic based on the age. If the age of the
first object is greater than the second, we are returning a positive value. It
can be anyone such as 1, 2, 10. If the age of the first object is less than the
second object, we are returning a negative value, it can be any negative
value, and if the age of both objects is equal, we are returning 0.
import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
} }
NameComparator.java
This class provides comparison logic based on the name. In such case,
we are using the compareTo() method of String class, which internally
provides the comparison logic.
import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
} }
Simple.java

In this class, we are printing the values of the object by sorting on the
basis of name and age.
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("Sorting by age");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
} } }
Output:
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27
1.16 COMPARABLE VS COMPARATOR
Comparable and Comparator both are interfaces and can be used to
sort collection elements.However, there are many differences between
Comparable and Comparator interfaces that are given below.

You might also like