Unit 4
Unit 4
Unit-4
What is Collection in Java
A collection is a group of objects. In Java, these objects are called elements of the collection.
For Example:
1. A classroom is a collection of students. So, the classroom is nothing but a collection and students are
objects.
2. We know that the entire world is a collection of humans, animals, and different things. The world is a
collection and humans, animals and different things are different objects.
Technically, a collection is an object or container which stores a group of other objects as a single unit or
single entity. Therefore, it is also known as container object or collection object in java.
A container object means it contains other objects. In simple words, a collection is a container that stores
multiple elements together.
JVM (Java Virtual Machine) stores the reference of other objects into a collection object. It never stores
physical copies of other objects because other objects are already available in the memory and storing another
copy of objects into a collection object would be a wasting of memory.
A collection object has a class that is known as collection class or container class. All collection classes are
present in java.util package.
A collection object has a class that is known as collection class or container class. All collection classes are
present in java.util package.
A simple example of a collection is:
// Create a container list of cities (objects or elements).
List<String> city = new ArrayList<String>();
1
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
There are two types of objects that can be stored in a collection or container object. They are as follows:
1. Homogeneous objects:
Homo means same. Homogeneous objects are a group of multiple objects that belong to the same class.
For example, suppose we have created three objects Student s1, Student s2, and Student s3 of the same class
‘Student’. Since these three objects belong to the same class that’s why they are called homogeneous objects.
2. Heterogeneous objects:
Hetero means different. Heterogeneous objects are a group of different objects that belong to different classes.
For example, suppose we have created two different objects of different classes such as one object Student s1,
and another one object Employee e1. Here, student and employee objects together are called a collection of
heterogeneous objects.
These objects can also be further divided into two types. They are as follows:
1. Duplicate objects:
The multiple objects of a class that contains the same data are called duplicate objects. For example, suppose
we create two person objects Person p1 and Person p2. Both of these objects have the same data.
Person p1 = new Person( "abc");
Person p2 = new Person("abc");
2. Unique objects:
Since the above two objects have the same data “abc” therefore, these are called duplicate objects.
The multiple objects of a class that contains different data are called unique objects. For example:
Person p1 = new Person("abcd");
Person p2 = new Person("abcde");
A unique or duplicate object depends on its internal data.
2
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
For storing one value we need to create one variable and assign a value0, like this: int x = 10;
The purpose of variable x is to store one int value 10. If we want to store two int values, we will create
two variables like this:
int x = 10;
int y = 20;
Similarly, for three values, the third variable will be required, and so on.
There is no problem to store until the third or fourth value. But if we want to store 5000 values then
declaring 5000 variables in a program is the worst kind of programming practice.
Using a class object, we can store multiple “fixed” number of values of different types. For example,
suppose we have created a class named Employee and declare two variables inside the class.
class Employee
{
int eNo;
String eName;
}
This employee object can store only two values but if we will want to store the third value, it will not
possible. Therefore, this approach is only suitable to store a fixed number of different values.
3
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
To overcome this problem, we should use the third technique “Array object”.
We can store a group of objects into an array. Suppose we want to store 5000 objects of Student class into
an array.
For this purpose, we need to create an array object of Student type like this:
Student[ ] st = new Student[5000];
The biggest advantage of an array is that we can store a huge number of values by using a single variable
st and retrieve them easily.
Array mechanism helps to improve the readability of the code in java programming but there are several
types of problems and limitations with the array. They are as follows:
1. We can easily store multiple “fixed” numbers of values of homogeneous data type i.e. an array can store
only similar types of data. Suppose if we create an Employee type array object like this:
Employee[ ] emp = new Employee[5000]; // It will hold only employee type objects.
For example:
emp[0] = new Employee(); // valid.
emp[1] = new Customer(); // invalid because here, we are providing the customer type object.
2. An array is static in nature. It is fixed in length and size. We cannot change (increase/decrease) the size of
the array based on our requirements once they created.
3. We can add elements at the end of an array easily. But, adding and deleting elements or objects in the
middle of array is difficult.
4. We cannot insert elements in some sorting order using array concept because array does not support any
method. We will have to write the sorting code for this but in the case of collection, ready-made method
support is available for sorting using Tree set.
5. We cannot search a particular element using an array, whether the particular element is present or not in
the array index. For this, we will have to write the searching code using array but in the case of collection,
one readymade method called contains() method is available.
Due to all these above limitations of array, programmers need a better mechanism to store a group of objects.
So, the alternative option is a collection object or container object in java.
4. Using collection object:
By using collection object, we can store the same or different data without any size limitation. Thus,
technically, we can define the collections as:
A collection in Java is a container object that is used for storing multiple homogeneous and heterogeneous,
duplicate, and unique elements without any size limitation.
Framework in java
Java frameworks are the prewritten code used by developers to create applications in the java language.
5
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
It saves developers time and effort by providing efficient implementations of common data structures. In
multi-threaded environments, working with collections can be challenging because of the possibility of race
conditions and other concurrency issues.
6
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
→The Map interface is also part of the java collection framework but it does not inherit the collection interface.
The map interface is preferred when values are stored in the form of keys and value pairs.
Map Interface implemented using following classes:-
• Hashmap
• LinkedHashmap
• HashTable
These interfaces provide different ways of managing groups of objects, depending on the requirements.
1. List Interface
The List interface is an ordered collection that allows us to add and remove elements like an array.
2. Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have
duplicate elements.
3. Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner.
4. Java Map Interface
In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique names that can be
used to access a particular element in a map. And, each key has a single value associated with it.
7
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Some of the most commonly used implementations of the Collections Framework in Java are as:
• ArrayList
• LinkedList
• HashSet
• HashMap
• TreeMap
• TreeSet
8
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
The hierarchy of the entire collection framework consists of four core interfaces such as Collection, List, Set,
Map, and two specialized interfaces named SortedSet and SortedMap for sorting.
All the interfaces and classes for the collection framework are located in java.util package.
9
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
e➝ extends, I➝ implements
Extends: Extends is a keyword that is used for developing inheritance between two classes and two interfaces.
Implements: Implements is a keyword used for developing inheritance between class and interface
1. The basic interface of the collections framework is the Collection interface which is the root interface of
all collections in the API (Application Programming Interface).
It is placed at the top of the collection hierarchy in java. It provides the basic operations for adding and
removing elements in the collection.
2. Collection interface extends the Iterable interface. The iterable interface has only one method called
iterator(). The function of the iterator method is to return the iterator object. Using this iterator object, we
can iterate over the elements of the collection.
10
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
3. List, Queue, and Set have three components which extends the Collection interface. A map is not inherited
by Collection interface.
For example, the ArrayList class implements the List interface which is a subinterface of
the Collection Interface.
11
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
To remove all the collection elements that are not contained in the
5 retain(collection c)
specified collection.
9 equals(collection c) It is used to check if the two collections are the same or not.
The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have
duplicate elements.
Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner.
The Iterator interface of the Java collections framework allows us to access elements of a collection. It has a
subinterface ListIterator.
All the Java collections include an iterator() method. This method returns an instance of iterator used to
iterate over elements of collections.
13
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Methods of Iterator
The Iterator interface provides 4 methods that can be used to perform various operations on elements of
collections.
• hasNext() - returns true if there exists an element in the collection
• next() - returns the next element of the collection
• remove() - removes the last element returned by the next()
• forEachRemaining() - performs the specified action for each remaining element of the collection
import java.util.ArrayList;
import java.util.Iterator;
14
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
}
}
The List interface provides a listIterator() method that returns an instance of the ListIterator interface.
Methods of ListIterator
The ListIterator interface provides methods that can be used to perform various operations on the elements of
a list.
• hasNext() - returns true if there exists an element in the list
• next() - returns the next element of the list
• nextIndex() returns the index of the element that the next() method will return
• previous() - returns the previous element of the list
• previousIndex() - returns the index of the element that the previous() method will return
15
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.util.ArrayList;
import java.util.ListIterator;
class collframe2 {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(7);
numbers.add(9);
numbers.add(5);
System.out.println("ArrayList: " + numbers);
16
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
List interface
List is the child interface of Collection interface. If we want to represent a group of individual objects as single
entity where duplicates are allowed and insertion order must be preserved, They appear in the same order in
which we inserted.
List Interface is implemented by using :
• ArrayList
• LinkedList
• Vector
• Stack
These classes are defined in the Collections framework and implement the List interface.
ArrayList
Methods in ArrayList:
17
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Example1:
import java.util.List;
import java.util.ArrayList;
class arryl1 {
public static void main(String[] args) {
// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();
18
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
LinkedList
Linked List is a part of the Collection framework present in java.util package. This class is an implementation
of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous
locations and every element is a separate object with a data part and address part. The elements are linked
using pointers and addresses. Each element is known as a node.
• LinkedList class uses a doubly LinkedList to store element. i.e., the user can add data at the first
position as well as the last position.
• The dequeue interface is implemented using the LinkedList class.
• Null insertion is possible.
• If we need to perform insertion /Deletion operation the LinkedList is preferred.
• LinkedList is used to implement Stacks and Queues.
Creation of a LinkedList
LinkedList<DataType> VariableName = new LinkedList < DataType>();
19
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Example1:
20
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.util.LinkedList;
class Linklist1 {
public static void main(String[] args){
// create linkedlist
LinkedList<String> pl = new LinkedList<>();
Example:2
import java.util.List;
import java.util.LinkedList;
class linklist {
21
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Example-3
import java.util.*;
public class Linklist2
{
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("C");
list.add("C++");
list.add("Python");
list.add("Java");
list.add("PHP");
System.out.println("Original list is: "+ list);
list.addFirst("scala");
list.addFirst("HTML");
System.out.println("After adding element by using addFirst() method: " + list);
list.removeFirst();
System.out.println("After adding element by using removeFirst() method: " + list);
System.out.println("After adding element by using getFirst() method: " + list.getFirst());
list.addLast("CSS");
System.out.println("After adding element by using addLast() method: " + list);
list.removeLast();
System.out.println("After adding element by using removeLast() method: " + list);
System.out.println("After adding element by using getLast() method: " + list.getLast());
}
}
22
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Java Vector
The Vector class is an implementation of the List interface that allows us to create resizable-arrays similar to
the ArrayList class.
In Java, both ArrayList and Vector implements the List interface and provides the same functionalities.
However, there exist some differences between them.
The Vector class synchronizes each individual operation. This means whenever we want to perform some
operation on vectors, the Vector class automatically applies a lock to that operation.
It is because when one thread is accessing a vector, and at the same time another thread tries to access it, an
exception called ConcurrentModificationException is generated. Hence, this continuous use of lock for each
operation makes vectors less efficient.
Creation of Vector:
Vector < DataType> VariableName = new Vector<DataType> ();
23
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.util.Iterator;
import java.util.Vector;
class Vectorlist {
public static void main(String[] args) {
Vector<String> pl= new Vector<>();
24
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
// Using addAll()
Vector<String> course = new Vector<>();
course.add("B.Tech");
System.out.println("New Vector: " + course);
course.addAll(pl);
System.out.println("Now Vector is: " + course);
// Using iterator()
Iterator<String> iterate = course.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
// Using remove()
String ele = course.remove(1);
System.out.println("Removed Element: " + ele);
System.out.println("New Vector: " + course);
// Using clear()
course.clear();
System.out.println("Vector after clear(): " + course);
}
}
25
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
The Java collections framework has a class named Stack that provides the functionality of the stack data
structure.
The Stack class extends the Vector class.
Stack Implementation
In stack, elements are stored and accessed in Last In First Out manner. That is, elements are added to the
top of the stack and removed from the top of the stack.
26
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Creating a Stack:
In order to create a stack, we must import the java.util.Stack package first. Once we import the package,
here is how we can create a stack in Java.
Method Description
empty() It returns true if nothing is on the top of the stack. Else, returns false.
peek() Returns the element on the top of the stack, but does not remove it.
import java.util.Stack;
27
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
}
}
Queue Interface
The Queue interface of the Java collections framework provides the functionality of the queue data structure.
It extends the Collection interface. It is used to store elements that are going to be processed in First In First
Out (FIFO) order.
It adheres to the First-In-First-Out, or FIFO, concept, queue is an ordered collection of the homogeneous
group of elements in which new elements are added at one end(rear) and elements are removed from the other
end(front).
29
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
30
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Methods of Queue
The Queue interface includes all the methods of the Collection interface. It is because Collection is the super
interface of Queue.
Some of the commonly used methods of the Queue interface are:
• add() - Inserts the specified element into the queue. If the task is successful, add() returns true, if not
it throws an exception.
• offer() - Inserts the specified element into the queue. If the task is successful, offer() returns true, if
not it returns false.
• element() - Returns the head of the queue. Throws an exception if the queue is empty.
• peek() - Returns the head of the queue. Returns null if the queue is empty.
• remove() - Returns and removes the head of the queue. Throws an exception if the queue is empty.
• poll() - Returns and removes the head of the queue. Returns null if the queue is empty.
class Queueimp1 {
31
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
class Queueimp2 {
32
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Set Interface
The set interface is present in java.util package and extends the Collection interface. It is an unordered
collection of objects in which duplicate values cannot be stored. It is an interface that implements the
mathematical set. This interface contains the methods inherited from the Collection interface and adds a
feature that restricts the insertion of the duplicate elements.
There are two interfaces that extend the set implementation namely SortedSet and NavigableSet.
Characteristics Of A Set:
1. No Duplicates:
2. Unordered Collection
3. Single Null Value:
Classes that implement Set
33
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Creation of Set:
In Java, we must import java.util.Set package in order to use Set.
// Set implementation using HashSet
Set<String> Subject = new HashSet<>();
Methods of Set
The Set interface includes all the methods of the Collection interface. It's because Collection is a super
interface of Set.
34
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Some of the commonly used methods of the Collection interface that's also available in the Set interface are:
• add() - adds the specified element to the set
• addAll() - adds all the elements of the specified collection to the set
• iterator() - returns an iterator that can be used to access elements of the set sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another specified set
• retainAll() - retains all the elements in the set that are also present in another specified set
• clear() - removes all the elements from the set
• size() - returns the length (number of elements) of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element
• containsAll() - returns true if the set contains all the elements of the specified collection
• hashCode() - returns a hash code value (address of the element in the set)
Set Operations
The Java Set interface allows us to perform basic mathematical set operations like union, intersection, and
subset.
• Union - to get the union of two sets x and y, we can use x.addAll(y)
• Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
• Subset - to check if x is a subset of y, we can use y.containsAll(x)
import java.util.Set;
import java.util.HashSet;
class Setimp1 {
// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);
class Setimp2 {
36
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
}
}
Creating a HashSet
In order to create a hash set, we must import the java.util.HashSet package first.
Once we import the package, here is how we can create hash sets in Java.
1. HashSet h = new HashSet(); is the default constructor. Default initial capacity is 16, load factor is 0.75.
2. HashSet h = new HashSet(int initialCapacity) is a constructor with a given initial capacity. The load
factor is 0.75.
3. HashSet h = new HashSet(int initialCapacity, float loadFactor);is a constructor with a given initial
capacity and load factor.
4. HashSet h = new HashSet(Collection C)is a constructor that adds elements from another collection
37
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
By default,
• the capacity of the hash set will be 16
• the load factor will be 0.75
Methods in HashSet
Method Description
Implementation of Hashset
import java.util.*;
38
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
class Hashsetimp1
{
public static void main(String[]args)
{
HashSet<String> h = new HashSet<String>();
39
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Set Operations
The various methods of the HashSet class can also be used to perform various set operations.
Union of Sets
To perform the union between two sets, we can use the addAll() method. For example,
import java.util.HashSet;
class Hashsetimp2 {
public static void main(String[] args) {
HashSet<Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("HashSet1: " + evenNumbers);
40
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method. For example
import java.util.HashSet;
class Hashsetimp3 {
public static void main(String[] args) {
HashSet<Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("HashSet1: " + primeNumbers);
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method. For example,
Subset
To check if a set is a subset of another set or not, we can use the containsAll() method.
Java LinkedHashSet
The LinkedHashSet class of the Java collections framework provides functionalities of both the hashtable and
the linked list data structure.It implements the Set interface. Elements of LinkedHashSet are stored in hash
tables similar to HashSet.
41
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
However, linked hash sets maintain a doubly-linked list internally for all of its elements. The linked list defines
the order in which elements are inserted in hash tables.
We can create LinkedHashSet by using one of its four constructors. They are as follows:
2. LinkedHashSet(Collection c): This constructor is used to initialize the LinkedHashSet with elements of
collection c. The general syntax is as follow:
Methods of LinkedHashSet
The LinkedHashSet class provides methods that allow us to perform various operations on the linked hash
set.
Insert Elements to LinkedHashSet
• add() - inserts the specified element to the linked hash set
• addAll() - inserts all the elements of the specified collection to the linked hash set
42
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Union of Sets
Two perform the union between two sets, we can use the addAll() method.
Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method.
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method.
Subset
To check if a set is a subset of another set or not, we can use the containsAll() method.
Method Description
clone() Creates a copy of the LinkedHashSet
contains() Searches the LinkedHashSet for the specified element and returns a boolean result
isEmpty() Checks if the LinkedHashSet is empty
size() Returns the size of the LinkedHashSet
clear() Removes all the elements from the LinkedHashSet
Both LinkedHashSet and HashSet implements the Set interface. However, there exist some differences
between them.
• LinkedHashSet maintains a linked list internally. Due to this, it maintains the insertion order of its
elements.
• The LinkedHashSet class requires more storage than HashSet. This is
because LinkedHashSet maintains linked lists internally.
• The performance of LinkedHashSet is slower than HashSet. It is because of linked lists present
in LinkedHashSet.
import java.util.Iterator;
import java.util.LinkedHashSet;
class Linkhashsetimp1
{
public static void main(String[] args) {
LinkedHashSet<Integer> evenNumber = new LinkedHashSet<>();
// Accessing elements
while(iterate.hasNext())
{
System.out.print(iterate.next());
System.out.print(", ");
}
//Remove Elements
// Using the remove() method
boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);
boolean value2 = numbers.removeAll(numbers);
System.out.println("Are all elements removed? " + value2);
//union of two sets
LinkedHashSet<Integer> evenNum = new LinkedHashSet<>();
evenNum.add(2);
evenNum.add(4);
System.out.println("LinkedHashSet1: " + evenNum);
num.retainAll(evenNum);
System.out.println("Intersection is: " + num);
//Subset
// Check if num is a subset of even
LinkedHashSet<Integer> even = new LinkedHashSet<>();
even.add(2);
even.add(4);
even.add(6);
boolean result = even.containsAll(num);
System.out.println("Is num is subset of even ? " + result);
}
}
The SortedSet interface present in java.util package extends the Set interface present in the collection
framework. It is an interface that implements the mathematical set. This interface contains the methods
inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in
a sorted manner.
45
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Methods of SortedSet
The SortedSet interface includes all the methods of the Set interface. It's because Set is a super interface
of SortedSet.
Besides methods included in the Set interface, the SortedSet interface also includes these methods:
• comparator() - returns a comparator that can be used to order elements in the set
• first() - returns the first element of the set
• last() - returns the last element of the set
• headSet(element) - returns all the elements of the set before the specified element
• tailSet(element) - returns all the elements of the set after the specified element including the
specified element
• subSet(element1, element2) - returns all the elements between
the element1 and element2 including element1
import java.util.SortedSet;
import java.util.TreeSet;
class Sortedsetimp1 {
46
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
// Remove elements
boolean result = numbers.remove(2);
System.out.println("Is the number 2 removed? " + result);
}
}
TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for
storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an
explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set
interface.
It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used.
The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.
Hierarchy Diagram of TreeSet
Creating a TreeSet
47
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
48
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
• floor(element) - Returns the greatest element among those elements that are less than the
specified element. If the element passed exists in a tree set, it returns the element passed as an
argument.
3. pollfirst() and pollLast() Methods
• pollFirst() - returns and removes the first element from the set
• pollLast() - returns and removes the last element from the set
4. headSet(element, booleanValue)
The headSet() method returns all the elements of a tree set before the specified element (which is passed as an
argument).
The booleanValue parameter is optional. Its default value is false.
If true is passed as a booleanValue, the method returns all the elements before the specified element including
the specified element.
5. tailSet(element, booleanValue)
The tailSet() method returns all the elements of a tree set after the specified element (which is passed as a
parameter) including the specified element.
The booleanValue parameter is optional. Its default value is true.
If false is passed as a booleanValue, the method returns all the elements after the specified element without
including the specified element.
Set operations
The methods of the TreeSet class can also be used to perform various set operations.
Union of Sets
To perform the union between two sets, we use the addAll() method.
Intersection of Sets
To perform the intersection between two sets, we use the retainAll() method.
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method.
Subset of a Set
49
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
To check if a set is a subset of another set or not, we use the containsAll() method
50
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Methods of Map
The Map interface includes all the methods of the Collection interface. It is because Collection is a super
interface of Map.
Besides methods available in the Collection interface, the Map interface also includes the following
methods:
• put(K, V) - Inserts the association of a key K and a value V into the map. If the key is already
present, the new value replaces the old value.
51
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
• putAll() - Inserts all the entries from the specified map to this map.
• putIfAbsent(K, V) - Inserts the association if the key K is not already associated with the value V.
• get(K) - Returns the value associated with the specified key K. If the key is not found, it returns null.
• getOrDefault(K, defaultValue) - Returns the value associated with the specified key K. If the key is
not found, it returns the defaultValue.
• containsKey(K) - Checks if the specified key K is present in the map or not.
• containsValue(V) - Checks if the specified value V is present in the map or not.
• replace(K, V) - Replace the value of the key K with the new specified value V.
• replace(K, oldValue, newValue) - Replaces the value of the key K with the new value newValue only
if the key K is associated with the value oldValue.
• remove(K) - Removes the entry from the map represented by the key K.
• remove(K, V) - Removes the entry from the map that has key K associated with value V.
• keySet() - Returns a set of all the keys present in a map.
• values() - Returns a set of all the values present in a map.
• entrySet() - Returns a set of all the key/value mapping present in a map.
import java.util.Map;
import java.util.HashMap;
class Mapimp1 {
import java.util.Map;
import java.util.TreeMap;
class Mapimp2 {
53
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Java HashMap
Java HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but
there should be only one null key object and there can be any number of null values. This class makes no
guarantees as to the order of the map The HashMap class implements the Map interface.
Create a HashMap
In order to create a hash map, we must import the java.util.HashMap package first. Once we import the
package, here is how we can create hashmaps in Java.
// hashMap creation with 8 capacity and 0.6 load factor
HashMap<K, V> numbers = new HashMap<>();
Here, K represents the key type and V represents the type of values.
HashMap<String, Integer> numbers = new HashMap<>();
Here, the type of keys is String and the type of values is Integer.
54
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Note: While creating a hashmap, we can include optional parameters: capacity and load factor. For
example,
HashMap<K, V> numbers = new HashMap<>(8, 0.6f);
Here,
• 8 (capacity is 8) - This means it can store 8 entries.
• 0.6f (load factor is 0.6) - This means whenever our hash table is filled by 60%, the entries are moved
to a new hash table double the size of the original hash table.
If the optional parameters not used, then the default capacity will be 16 and the default load factor will
be 0.75.
import java.util.HashMap;
class Hashmapimp1 {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();
The HashMap class provides various methods to perform different operations on hashmaps.
• Add elements
• Access elements
• Change elements
• Remove elements
import java.util.HashMap;
import java.util.Map;
// 2. Access an element
int value = map.get("Two");
System.out.println("Value for key 'Two': " + value);
// 5. Remove an element
map.remove("One");
System.out.println("HashMap after removing key 'One': " + map);
// 6. Replace an element
map.replace("Two", 22);
System.out.println("HashMap after replacing value for key 'Two': " + map);
LinkedHashMap in Java
The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of
elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it
never maintained the track and order of insertion, which the LinkedHashMap provides where the elements
can be accessed in their insertion order.
57
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Creating a LinkedHashMap
In order to create a linked hashmap, we must import the java.util.LinkedHashMap package first. Once we
import the package, here is how we can create linked hashmaps in Java.
Here,
• Key - a unique identifier used to associate each element (value) in a map
• Value - elements associated by the keys in a map
Notice the part new LinkedHashMap<>(8, 0.6). Here, the first parameter is capacity and the second
parameter is loadFactor.
By default,
• the capacity of the linked hashmap will be 16
• the load factor will be 0.75
import java.util.LinkedHashMap;
class Linkhashmapimp1 {
public static void main(String[] args) {
// Creating a LinkedHashMap of even numbers
LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("LinkedHashMap1: " + evenNumbers);
numbers.put("Three", 3);
System.out.println("LinkedHashMap2: " + numbers);
}
}
Methods of LinkedHashMap
The LinkedHashMap class provides methods that allow us to perform various operations on the map.
containsKey() checks if the map contains the specified key and returns a boolean value
containsValue() checks if the map contains the specified value and returns a boolean value
size() returns the size of the map
isEmpty() checks if the map is empty and returns a boolean value
Both the LinkedHashMap and the HashMap implements the Map interface. However, there exist some
differences between them.
• LinkedHashMap maintains a doubly-linked list internally. Due to this, it maintains the insertion order
of its elements.
• The LinkedHashMap class requires more storage than HashMap. This is
because LinkedHashMap maintains linked lists internally.
• The performance of LinkedHashMap is slower than HashMap.
import java.util.LinkedHashMap;
import java.util.Map;
// 2. Access an element
int value = map.get("Two");
System.out.println("Value for key 'Two': " + value);
// 5. Remove an element
map.remove("One");
60
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
// 6. Replace an element
map.replace("Two", 22);
System.out.println("LinkedHashMap after replacing value for key 'Two': " + map);
TreeMap in Java
The TreeMap class of the Java collections framework provides the tree data structure implementation.
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-
value pairs in sorted order.
o Java TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
o Java TreeMap contains only unique elements.
62
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.
Creating a TreeMap
In order to create a TreeMap, we must import the java.util.TreeMap package first.
Here,
• Key - a unique identifier used to associate each element (value) in a map
• Value - elements associated by keys in a map
Methods of TreeMap
The TreeMap class provides various methods that allow us to perform operations on the map.
// 2. Access an element
int value = map.get("Two");
System.out.println("Value for key 'Two': " + value);
// 5. Remove an element
map.remove("One");
System.out.println("TreeMap after removing key 'One': " + map);
// 6. Replace an element
map.replace("Two", 22);
System.out.println("TreeMap after replacing value for key 'Two': " + map);
map.clear();
System.out.println("TreeMap after clearing: " + map);
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as
a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must
implement the hashCode method and the equals method.
The Hashtable class in Java is a concrete implementation of a Dictionary and was originally part of the java.util
package. It creates a hash table by mapping keys to values
The java.util.Hashtable class is a class in Java that provides a key-value data structure, similar to the Map
interface. It was part of the original Java Collections framework and was introduced in Java 1.0.
However, the Hashtable class has since been considered obsolete and its use is generally discouraged. This is
because it was designed prior to the introduction of the Collections framework and does not implement the
Map interface, which makes it difficult to use in conjunction with other parts of the framework.
66
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
In addition, the Hashtable class is synchronized, which can result in slower performance compared to other
implementations of the Map interface.
In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap or
ConcurrentHashMap) instead of the Hashtable class.
This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11.
This creates a hash table that has an initial size specified by initialCapacity and the default load factor is
0.75.
This version creates a hash table that has an initial size specified by size and fill ratio specified by fillRatio.
fill ratio: Basically, it determines how full a hash table can be before it is resized upward and its Value lies
between 0.0 to 1.0.
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
// 2. Access an element
int value = table.get("Two");
System.out.println("Value for key 'Two': " + value);
// 5. Remove an element
table.remove("One");
System.out.println("Hashtable after removing key 'One': " + table);
// 6. Replace an element
table.replace("Two", 22);
System.out.println("Hashtable after replacing value for key 'Two': " + table);
Sorting in Java
The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or
descending order. The numerical and lexicographical (alphabetical) order is a widely used order.
Java provides several built-in methods and algorithms for sorting arrays efficiently.
69
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
//Initialize array
int [] arr = new int [] {10, 40, 30, 20};
int temp = 0;
70
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Java provides a built-in method, Arrays.sort(), to sort an array. This method sorts the array’s elements into
ascending order, applicable to different types of arrays such as integer, double, string, or custom objects.
The Arrays.sort() method uses a variation of the QuickSort algorithm, known for its efficiency in most
common scenarios.
import java.util.Arrays;
// Main class
public class sortingimp2
{
al.add("DBMS");
al.add("HTML");
al.add("SQL");
import java.util.Arrays;
// Main class
public class sortingimp4
{
Note:
• Which sorting algorithm does Java use in sort()?
73
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for
arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort.
Comparable Interface
The Comparable interface is used to compare an object of the same class with an instance of that class, it
provides ordering of data for objects of the user-defined class. The class has to implement
the java.lang.Comparable interface to compare its instance, it provides the compareTo method that takes a
parameter of the object of that class.
The compareTo method required by the Comparable interface receives as its parameter the object to which
the "this" object is compared.
If the "this" object comes before the object received as a parameter in terms of sorting order, the method should
return a negative number.
If, on the other hand, the "this" object comes after the object received as a parameter, the method should return
a positive number. Otherwise, 0 is returned.
The sorting resulting from the compareTo method is called natural ordering
Syntax
class MyClass implements Comparable<MyClass> {
// Class body.
...
@Override public int compareTo(MyClass value)
74
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
{
// Comparison Logic
...
return result;
}
}
This interface has a single .compareTo() method that returns an int value based on whether the value of a
current class instance (referenced by this) can be logically sorted with the value of another instance of the
same class.
The compareTo method should follow the contract defined by the Comparable interface. The comparison
logic should be consistent with the equals method (i.e., if compareTo returns 0, equals should return true).
Return Value Meaning
>= 1 this instance > passed instance
0 this instance = passed instance
<= -1 this instance < passed instance
Implementation
Given an array of Pairs consisting of two fields of type string and integer. you have to sort the array in
ascending Lexicographical order and if two strings are the same sort it based on their integer value.
Sample I/O:
Input: { {"abc", 3}, {"a", 4}, {"bc", 5}, {"a", 2} }
Output: { {"a", 2}, {"a", 4}, {"abc", 3}, {"bc", 5} }
Implemenation-1
import java.io.*;
import java.util.*;
75
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
int n = 4;
Member arr[] = new Member[n];
// printing the
// Pair array
76
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
print(arr);
}
Implemenation-2
import java.io.*;
import java.util.*;
int n = 4;
Member1 arr[] = new Member1[n];
// printing the
// Pair array
print(arr);
}
Example 2
Given an array of Pairs consisting of two strings with first and last names. you have to sort the array in
ascending Lexicographical order of the first name and if two strings are the same sort it based on their last
name.
Sample I/O:
Input: { {"raj", "kashup"}, {"rahul", "singh"}, {"reshmi", "dubey"}, {"rahul", "jetli"} }
Output: { {"rahul", "jetli"}, {"rahul", "singh"}, {"raj", "kashup"}, {"reshmi", "dubey"} }
78
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.io.*;
import java.util.*;
int n = 4;
Member3 arr[] = new Member3[n];
arr[0] = new Member3("raj", "kashup");
arr[1] = new Member3("rahul", "singh");
arr[2] = new Member3("reshmi", "dubey");
arr[3] = new Member3("rahul", "jetli");
79
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
// printing the
// Pair array
print(arr);
}
Syntax
class MyComparator implements Comparator<MyClass> {
@Override public int compare(MyClass a, MyClass b)
{
// Compare logic
...
80
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
return result;
}
}
Applying the Comparator interface to a class, MyComparator, requires the implements keyword
(e.g., Comparator<MyClass>). This interface has a .compare() method that returns an int value based on
whether two MyClass instances, a and b, can be logically sorted.
A Comparator class can be passed as an argument to methods such as Arrays.sort() and Collections.sort() to
specify the sort order, potentially overriding the natural sort order defined by the class’s
own .compareTo() method.
Method Description
public int compare(Object obj1, Object obj2) It compares the first object with the second object.
public boolean equals(Object obj) It is used to compare the current object with the specified
object.
// Class 1
// Helper class representing a Student
81
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
class Student {
// Attributes of student
String Name;
int Age;
// Parameterized constructor
public Student(String Name, Integer Age)
{
// Method
// Overriding toString() method
@Override public String toString()
{
return "Customer{"
+ "Name=" + Name + ", Age=" + Age + '}';
}
}
// Class 2
// Helper class implementing Comparator interface
class CustomerSortingComparator implements Comparator<Student>
{
// Method 1
// To compare customers
@Override
public int compare(Student customer1, Student customer2)
{
// Comparing customers
int NameCompare = customer1.getName().compareTo(customer2.getName());
82
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
// Method 2
// Main driver method
class comparatorinterfaceimp1
{
public static void main(String[] args)
{
// Display message
System.out.println("Before Sorting:\n");
while (custIterator.hasNext()) {
Properties class is the child class of Hashtable. It works in conjunction with properties file which is a text
file. A properties file contains key-value in text format.
The Properties class in Java is a subclass of Hashtable that is used to maintain lists of values in which the key
is a string and the value is also a string. This class is often used for configuration and storing settings for
applications.
The Properties class is a powerful tool for managing application configuration and settings, making it easy to
load, save, and manipulate key-value pairs in your Java applications.
84
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Methods
Java Properties is a type of class which includes the following methods within it:
• String getProperty(String Key)
• String getProperty(String key, String defaultProperty)
• voidList(PrintStream streamOut)
• voidList(PrintWriter streamOut)
• voidload(InputStream streamIn) throws IO Exception
• Enumeration propertyNames()
• ObjectSetProerty(String key, StringValue)
• void store(Output Stream streamOut, String Description)
import java.util.*;
public class Propertyclassimp1
{
public static void main(String arg[])
{
Properties ex = new Properties();
Set url;
String str;
85
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
ex.put("aktu", "aktu.ac.in");
ex.put("result", "result.aktu.ac.in");
ex.put("syllabus", "syllabus.result.aktu.ac.in");
url = ex.keySet();
Iterator itr = url.iterator();
while(itr.hasNext())
{
str = (String)itr.next();
System.out.println("The url for " + str + " is " + ex.getProperty(str));
}
System.out.println();
str = ex.getProperty("syllabus", "not found");
System.out.println("This is the respective url for the syllabus " + str);
}
}
Example 2: The below program shows how to use the Properties class to get all the system properties.
Using System.getProperties() method, we can get all the properties of the system.
import java.util.*;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
// Set properties
87
SUDHAKAR DWIVEDI,IMSEC,CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
properties.setProperty("username", "admin");
properties.setProperty("password", "12345");
// Access properties
String username = loadedProperties.getProperty("username");
String password = loadedProperties.getProperty("password");
System.out.println("Loaded Properties:");
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}
88
SUDHAKAR DWIVEDI,IMSEC,CSE