0% found this document useful (0 votes)
31 views94 pages

22CS305- AJP UNIT1

java notes

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views94 pages

22CS305- AJP UNIT1

java notes

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

1

2
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the
educational purpose of RMK Group of Educational Institutions. If you have
received this document through email in error, please notify the system
manager. This document contains proprietary information and is intended
only for the respective group/learning community as intended. If you
are not the addressee you should not disseminate, distribute, or copy
through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from
your system. If you are not the intended recipient you are notified that
disclosing, copying, distributing, or taking any action in reliance on
the contents of this information is strictly prohibited.

3
22CS305
Advanced Java Programming
(Lab Integrated)
Department : CSE/IT/ADS/CSD/CSBS/ECE
Batch / Year : 2023 – 2027 / II
Created by : All Subject Handling Staff Members
Date : 15.06.2024

4
Table of Contents
Page
Sl.No. Topic
No.

1 Course Objectives 6

2 Syllabus 7

3 Pre-requisites 10

4 Course Outcomes 11

5 CO- PO Mapping 12

6 Lecture Plan 13

7 Activity-based learning 14

8 Lecture Notes 15

9 Assignments I - V 71 - 75

10 Part A Questions & Answers 76

11 Part B Questions 78

12 Supportive Online Certifications 79

13 Real-Time Applications 80

14 Content Beyond the Syllabus 81

15 Assessment Schedule 84

16 Prescribed Text Books & Reference Books 85

17 Mini Projects I - V 86-93

5
1. Course Objectives

OBJECTIVES: ( To be updated )

The Course will enable learners to:

❖ Gain a comprehensive understanding of the Java Collections Framework and its various

interfaces and implementations.

❖ Learn the details of Java I/O streams and utility classes for managing dates, numbers, and

currencies.

❖ Develop a thorough understanding of the Stream API introduced in Java 8 and its various

operations.

❖ Explore advanced object serialization and string tokenizing techniques, including pattern

matching with regular expressions.

❖ Understand advanced Stream API features and gain proficiency in using regular expressions

for text processing.

6
2. Syllabus
22CS305 ADVANCED JAVA PROGRAMMING (LAB INTEGRATED) L T P C
3 0 2 4
UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+6
Introduction to Collections Framework - Collection Interface- Methods in Collection
Interface - - Iterable and Iterator Interfaces - List Interface- ArrayList - LinkedList - Set
Interface - HashSet- LinkedHashSet - TreeSet - Map Interface - HashMap -
LinkedHashMap- TreeMap - Queue Interface -PriorityQueue - Deque Interface - Utility
Classes.
List of Exercises
1. Write a program that measures the time taken for insertion, deletion, and search
operations on ArrayList, LinkedList, HashSet, and TreeSet for varying sizes of input data.
2. Implement a custom data structure that combines features of a list and a set.
3. Write a Java program to create a HashMap where the keys are strings, and the values
are integers Add five key-value pairs to the map. Print all the keys and values in the
map. Remove an entry by key. Update the value associated with a specific key. Check
if the map contains a specific key and a specific value.
UNIT II I/O OPERATIONS, SERIALIZATION, AND DATE HANDLING 9+6
Date – Calendar – Comparable interface – Observer Interface – Streams - Types of
Streams - The Byte-stream I/O hierarchy - Character Stream Hierarchy – Random
Access File class – the java.io. Console Class – Serialization – Dates - Numbers, and
Currency - Working with Dates - Numbers and Currencies.
List of Exercises
1. Create a class representing a complex object with nested data structures.
Serialize the object to a file, then deserialize it back and verify that the object
remains intact.
2. Write a program that formats dates and currencies according to different locales.
3. Implement a java program that allows users to open a text file, navigate through
it using random access, insert, delete, and modify text at specific positions within the
file.

7
UNIT III STREAM API AND FUNCTIONAL PROGRAMMING 9+6
PARADIGMS
Overview of Stream API - Importance of Stream API in Java 8 and Beyond – Functional
Programming Concepts - Creating Streams - Stream Interface Methods - Stream
Operations- Intermediate Filtering (filter)-Mapping (map, flatMap)-Sorting (sorted)-
Distinct (distinct)- Limit and Skip (limit, skip) - Terminal Operations -Collecting Results
(collect) - Reducing and Summarizing (reduce, summaryStatistics)-Iterating (forEach) -
Matching and Finding (anyMatch, allMatch, noneMatch, findFirst, findAny) -Counting
(count).
List of Exercises
1. Write a program that performs stream operations like filtering, mapping, and reducing.
2. Create an infinite stream generator that generates prime numbers. Implement
methods to check for primality and generate the next prime number.
3. Write a program that reads a text file containing sentences. Tokenize each sentence
into words, filter out stopwords, and print the remaining words.
UNIT IV ADVANCED STRING PROCESSING, OBJECT SERIALIZATION, 9+6
AND I/O TECHNIQUES
String Tokenizer – Parsing - Tokenizing and Formatting - Locating Data via Pattern
Matching, Tokenizing - Object Serialization - Serializable Interface - Writing and Reading
Serializable Objects -Transient Keyword- SerialVersionUID - Advanced I/O - Piped
Streams (PipedInputStream and PipedOutputStream) – SequenceInputStream –
PushbackInputStream and PushbackReader.
List of Exercises
1. Write a program that reads a text file and tokenizes it into sentences using the
StringTokenizer class.
2. Create a class hierarchy representing different types of objects (e.g., Person,
Employee). Serialize instances of these classes to a file using object serialization.
3. Implement a program that uses advanced I/O techniques like PipedInputStream,
PipedOutputStream, SequenceInputStream, and PushbackInputStream.

8
UNIT V ADVANCED STREAM FEATURES AND REGULAR EXPRESSIONS 9+6
Importance and Use Cases of Advanced Stream Features - Creating Custom Streams –
Stream Generators (Stream.generate, Stream.iterate) - Infinite Streams -Using
Spliterators – Advanced Stream Operations - FlatMapping - Chaining Stream Operations
- Stream Peeking (peek) - Advanced Filtering Techniques- Introduction to Regular
Expressions - Character Classes - Quantifiers - Pattern Matching - Groups and Capturing
- Regex in Java - java.util.regex Package Pattern Class - Matcher Class - String
Manipulation with Regex - Splitting Strings - Replacing Text (replaceAll, replaceFirst) -
Replacing with Backreferences.

List of Exercises
1. Implement custom stream generators using Stream.generate and Stream.iterate
methods.
2. Write a program that demonstrates advanced stream operations like flatMapping,
chaining stream operations, and peeking.
3. Develop a program that utilizes regular expressions to perform string manipulation

tasks such as splitting strings, replacing text, and extracting specific patterns.

TOTAL: 45+30=75 PERIODS

TEXT BOOKS:
1.Cay S. Horstmann, "Core Java Volume I--Fundamentals," 12th Edition, 2019.
2.Joshua Bloch, "Effective Java," 3rd Edition, 2018.
3.Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams, and Functional-Style
Programming," 1st Edition, 2014.
4. Herbert Schildt, "Java: The Complete Reference," 11th Edition, 2018.
5. Alan Mycroft and Martin Odersky, "Programming in Scala," 4th Edition, 2020.

REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition, 2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional Programming”,
1st Edition, 2014.

9
3. Pre-requisites

22CS305 Advanced Java Programming

22CS202 – Java programming

22CS101 – problem solving using C++

10
4. Course Outcomes
At the end of this course, the students will be able to:

CO# Course Outcomes KL

Utilize the Java Collections Framework to solve complex data structure


CO1 K3
problems..
Demonstrate proficiency in Java I/O operations and manage data
CO2 K3
efficiently.
Learn to utilize the Stream API for complex data processing by applying
CO3 K3
functional programming techniques..

CO4 Understand and implement advanced object serialization techniques. K3

CO5 Effectively use regular expressions for advanced text processing tasks. K3

CO6 Build simple applications using advanced java programming concepts. K3

11
5. CO-PO Mapping

Program Status
Program Outcomes
Course Outcomes
Outcomes PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 3 3 - - - - - - - - - 3 2 2

CO2 3 2 2 - - - - - - - - - 3 3 2

CO3 3 2 2 - - - - - - - - - 3 3 2

CO4 3 2 2 - - - - - - - - - 3 3 2

CO5 3 2 2 - - - - - - - - - 3 3 2

CO6 3 2 2 - - - - - - - - - 3 3 2

12
6. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
Periods Date Date CO Delivery
. Level
Introduction to
As per
Collections As per
Time
Framework - Time table
table MD 1,
1,2 Collection 2 & CO1, CO6 K3
& MD 4
Interface- Methods Academic
Academic
in Collection Calendar
Calendar
Interface
As per
As per
Time
Time table
Iterable and table MD 1,
3 1 & CO1,CO6 K3
Iterator Interfaces & MD 4
Academic
Academic
Calendar
Calendar
As per
As per
Time
List Interface- Time table
table MD 1,
4 ArrayList - 1 & CO1, CO6 K3
& MD 4
LinkedList Academic
Academic
Calendar
Calendar
As per
As per
Set Interface - Time
Time table
HashSet- table MD 1,
5 1 & CO1, CO6 K3
LinkedHashSet - & MD 4
Academic
TreeSet Academic
Calendar
Calendar
As per
As per
Map Interface - Time
Time table
HashMap - table MD 1,
6,7 2 & CO1, CO6 K3
LinkedHashMap- & MD 4
Academic
TreeMap Academic
Calendar
Calendar
As per
As per
Time
Queue Interface - Time table
table MD 1,
8 PriorityQueue - 1 & CO1, CO6 K3
& MD 4
Deque Interface Academic
Academic
Calendar
Calendar
As per
As per
Time
Time table
table MD 1,
9 Utility Classes. 1 & CO1, CO6 K3
& MD 4
Academic
Academic
Calendar
Calendar
As per
As per
Time
10 Time table
table
- Lab Exercises 6 & CO1, CO6 K3 iamneo
&
15 Academic
Academic
Calendar
Calendar
* MD1 – Oral Presentation
13
* MD 4 – Hands on using any Java IDE
7. Activity Based Learning
Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems Practice At Home exercises posted in
iamneo Portal

Knowledge Check / MCQ Using


Learn by Questioning
iamneo portal and RMK Nextgen App

Learn by Hands on Practice available in iamneo Portal

Unit I Activity : - Mind Map Diagram

➢ Draw a detailed Mind Map diagram to create a visual representation which illustrates the

different classes and methods within Java Collections Framework . Include key details such as

interfaces, classes and their respective implementations, along with methods commonly used

for each type which provides a comprehensive overview of how collections are organized and

utilized in Java programming.

14
8. Lecture Notes
Introduction to Collections Framework :
1.1. Collection Interface:
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).
❑ A Collection represents a single unit of objects, i.e., a group.
❑ 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.
❑ Hierarchy of Collection Framework
❑ The java.util package contains all the classes and interfaces for the Collection
framework.

15
Fig. 1. Hierarchy of Collection Framework
8. Lecture Notes
1.2. Methods of Collection interface

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

Sl. No. Method Description


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

It is used to insert the specified collection


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

It is used to delete an element from the


3 public boolean remove(Object element)
collection.
It is used to delete all the elements of the
4 public boolean removeAll(Collection<?> c) specified collection from the invoking
collection.
It is used to delete all the elements of the
default boolean removeIf(Predicate<? super E>
5 collection that satisfy the specified
filter)
predicate.
It is used to delete all the elements of
6 public boolean retainAll(Collection<?> c) invoking collection except the specified
collection.
It returns the total number of elements in
7 public int size()
the collection.
It removes the total number of elements
8 public void clear()
from the collection.
9 public boolean contains(Object element) It is used to search an element.
It is used to search the specified collection
10 public boolean containsAll(Collection<?> c)
in the collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
It converts collection into array. Here, the
13 public <T> T[] toArray(T[] a) runtime type of the returned array is that
of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
It returns a possibly parallel Stream with
15 default Stream<E> parallelStream()
the collection as its source.
It returns a sequential Stream with the
16 default Stream<E> stream()
collection as its source.
It generates a Spliterator over the
17 default Spliterator<E> spliterator()
specified elements in the collection.
18 public boolean equals(Object element) It matches two collections.
It returns the hash code number of the
19 public int hashCode()
collection.

16
8. Lecture Notes
❑ Advantages of Collections
❑ Reduces programming effort : by providing useful data structures and algorithms so you don't
have to write them yourself.
❑ Increases performance : by providing high-performance implementations of useful data
structures and algorithms. Because the various implementations of each interface are
interchangeable, programs can be easily tuned by switching implementations.
❑ Provides interoperability between unrelated APIs: by establishing a common language to pass
collections back and forth.
❑ Reduces the effort required to learn APIs: by eliminating the need to learn multiple ad hoc
collection APIs.
❑ Reduces the effort required to design and implement APIs: by eliminating the need to produce
ad hoc collections APIs.
❑ Fosters Software reuse: by providing a standard interface for collections and algorithms to
manipulate them.

❖ Illustration of List, Set and Map

17
8. Lecture Notes
Framework in Java
❑ Collections framework provide a set of standard utility classes to manage collections
❑ Collections Framework consists of three parts:
❑ – Core Interfaces
❑ – Concrete Implementation
❑ – Algorithms such as searching and sorting
1.3. Iterable & Iterator interface
❑ 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.
❑ Iterator Interface:
❑ Iterator is an object that enables you to traverse through a collection.
❑ Can be used to remove elements from the collection selectively, if desired.
❑ There are only three methods in the Iterator interface.
❑ They are:

Sl.
Method Description
No.

It returns true if the iterator has more elements otherwise


1 public boolean hasNext()
it returns false.

It returns the element and moves the cursor pointer to the


2 public Object next()
next element.

It removes the last elements returned by the iterator. It is


3 public void remove()
less used.
Fig. 2. Methods in Iterator interface
1.4. List Interface
❑ List interface extends from Collection interface
❑ It stores elements in a sequential manner
❑ Elements in the list can be accessed or inserted based on their position
18
❑ Starts with zero based index
8. Lecture Notes
❑ Can contain duplicate elements

❑ An Iterator can be used to access the elements of the List

❑ To instantiate the List interface, we must use :

❑ List <data-type> list1= new ArrayList();

❑ List <data-type> list2 = new LinkedList();

❑ List <data-type> list3 = new Vector();

❑ List <data-type> list4 = new Stack();


❑ There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
❑ The classes that implement the List interface are given below.
❑ Array List
❑ Linked List
❑ Vector
❑ Stack
1.5. ArrayList:
❑ The ArrayList class implements the List interface.
❑ It uses a dynamic array to store the duplicate element of different data types.
❑ It is like an array, but there is no size limit. We can add or remove elements anytime.
❑ The ArrayList class maintains the insertion order and is non-synchronized.
❑ The elements stored in the ArrayList class can be randomly accessed because it works on
an index basis.
❑ In ArrayList, manipulation is a 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.
❑ We can not create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:
❑ ArrayList<int> al = ArrayList<int>(); // Not Valid
❑ ArrayList<Integer> al = new ArrayList<Integer>(); // Valid
❑ Example:
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating
19 arraylist
list.add("Roopa");//Adding object in arraylist
8. Lecture Notes
list.add(“Amudha");
list.add("Raji"); Output:
list.add("Ajay"); Roopa
Amudha
//Traversing list through Iterator Raji
Iterator itr=list.iterator(); Ajay

while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

❑ Constructors of ArrayList
Constructor Description
1. ArrayList() It is used to build an empty array list.
2. ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the
elements of the collection c.
3. ArrayList(int capacity) It is used to build an array list that has the specified
initial capacity.

❑ Methods of ArrayList

Method Description
boolean addAll(int index, It is used to append all the elements in the specified collection,
Collection<? extends E> c) 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 an ArrayList instance.
requiredCapacity)
It is used to fetch the element from the particular position of the
E get(int index)
list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
It is used to return the index in this list of the last occurrence of the
int lastIndexOf(Object o)
specified element, or -1 if the list does not contain this element.
It is used to return an array containing all of the elements in this list
Object[] toArray()
in the correct order.

20
8. Lecture Notes
Method Description

It is used to return an array containing all of the elements in this


<T> T[] toArray(T[] a)
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.

It is used to return the index in this list of the first occurrence of


int indexOf(Object o) the specified element, or -1 if the List does not contain this
element.

It is used to remove the element present at the specified position


E remove(int index)
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 from the list.
> c)

boolean removeIf(Predicate<? It is used to remove all the elements from the list that satisfies the
super E> filter) given predicate.

protected void removeRange(int


It is used to remove all the elements lies within the given range.
fromIndex, int toIndex)

void
It is used to replace all the elements from the list with the
replaceAll(UnaryOperator<E>
specified element.
operator)

It is used to retain all the elements in the list that are present in
void retainAll(Collection<?> c)
the specified collection.

It is used to replace the specified element in the list, present at


E set(int index, E element)
the specified position.

void sort(Comparator<? super It is used to sort the elements of the list on the basis of the
E> c) specified comparator.

Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list.

List<E> subList(int fromIndex,


It is used to fetch all the elements that lies within the given range.
int toIndex)

int size() It is used to return the number of elements present in the list.

It is used to trim the capacity of this ArrayList instance to be the


void trimToSize()
list's current size.
21
8. Lecture Notes
❑ Java ArrayList Example Programs:
❑ Program1 - //Printing the arraylist object
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
System.out.println(list); // //Printing the arraylist object
}
}
Output:
[Mango, Apple, Banana, Grapes]
Program2 - //Iterating ArrayList using For-each loop
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);

}
}
Output:
Mango
Apple
Banana
Grapes
22
8. Lecture Notes
❑ Program3 - //Get and Set ArrayList
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");
//accessing the element
System.out.println("Returning element: "+al.get(1));
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}
Output:
Returning element: Apple
Mango
Dates
Banana
Grapes
❖ QUIZ:
1. Which of the following classes is not implemented from the Collection
interface?
a. TreeSet
b. HashTable
c. Vector
d. Linked List
2. Which of the following is a class?
a. Collection
b. Collections
3. Which of the following does not accept duplicate values?
a. ArrayList
b. LinkedList
c. TreeSet
d. Vector

23
8. Lecture Notes
Program4 - //Sorting ArrayList
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51

24
8. Lecture Notes
❑ User-defined class objects in Java ArrayList
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
class ArrayList5{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
101 Sonoo 23
102 Ravi 21
25
103 Hanumat 25
8. Lecture Notes
❑ ArrayList example Program to remove elements
import java.util.*;
class ArrayList8 {
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
System.out.println("An initial list of elements: "+al);
//Removing specific element from arraylist
al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
//Creating another arraylist
ArrayList<String> al2=new ArrayList<String>(); Output:
al2.add("Ravi"); An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
al2.add("Hanumat"); After invoking remove(object) method: [Ravi, Ajay, Anuj,
Gaurav]
//Adding new elements to arraylist After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
al.addAll(al2); After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
System.out.println("Updated list : "+al); After invoking clear() method: []
//Removing all the new elements from arraylist
al.removeAll(al2);
System.out.println("After invoking removeAll() method: "+al);
//Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda expression
System.out.println("After invoking removeIf() method: "+al);
//Removing all the elements available in the list
al.clear();
System.out.println("After invoking clear() method: "+al);
}
26
}
8. Lecture Notes
❑ ArrayList example Program
import java.util.*;
public class ArrayListTest {
public static void main(String[] args) {
List<String> test = new ArrayList<String>();
String s = "hi";
test.add("string"); Output:
test.add(s); 3 false true 2
test.add(s+s);
System.out.print(test.size());
System.out.print(test.contains(42));
System.out.print(test.contains("hihi"));
test.remove("hi");
System.out.print(test.size());
}
}
❑ ListIterator() example Program
import java.util.*;
class ListIteratorExample { Output:

public static void main(String[] args) { Previous Index is : -1


ArrayList aList = new ArrayList(); Next Index is : 0
After increasing current position by one element :
//Add elements to ArrayList object Previous Index is : 0
aList.add("1"); Next Index is : 1

aList.add("2");
aList.add("3");
ListIterator listIterator = aList.listIterator();
System.out.println("Previous Index is : " + listIterator.previousIndex());
System.out.println("Next Index is : " + listIterator.nextIndex());
//advance current position by one using next method
listIterator.next();
System.out.println("After increasing current position by one element : ");
System.out.println("Previous Index is : " + listIterator.previousIndex());
System.out.println("Next Index is : " + listIterator.nextIndex());
}} 27
8. Lecture Notes
❑ ArrayList example Program with isEmpty()

import java.util.*;
class ArrayList10{

public static void main(String [] args)


{
ArrayList<String> al=new ArrayList<String>();
System.out.println("Is ArrayList Empty: "+al.isEmpty());
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After Insertion");
System.out.println("Is ArrayList Empty: "+al.isEmpty());
}
}
Output:

Is ArrayList Empty: true


After Insertion
Is ArrayList Empty: false

1.6. Linked List

❑ 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.
❑ 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.
Constructors of Java LinkedList:

Constructor Description

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

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.

28
8. Lecture Notes
❑ Methods of Java LinkedList
Method Description
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<? It is used to append all the elements in the specified
extends E> c) 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

29
8. Lecture Notes
❑ Methods of Java LinkedList
Method Description

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 It is used to remove the first occurrence of the specified element in
removeFirstOccurrence(Objec a list (when traversing the list from head to tail).
t o)
E removeLast() It removes and returns the last element from a list.
boolean It removes the last occurrence of the specified element in a list
removeLastOccurrence(Objec (when traversing the list from head to tail).
t o)
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).
<T> T[] toArray(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.

30
8. Lecture Notes
❑ Example Program1
import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Output:
[Volvo, BMW, Ford, Mazda]

❑ Example Program2

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

31
8. Lecture Notes
❑ Example Program3

import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);
//Adding an element at the first position
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);

}
}
32
8. Lecture Notes
Output:

Initial list of elements: []


After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

❑ Example Program4
import java.util.*;
public class LinkedList3 {

public static void main(String [] args)


{
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
ll.add("Anuj");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Virat");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
33
8. Lecture Notes
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list


ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}

Output:

Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

❑ Example Program5
import java.util.*;
public class LinkedList4{
public static void main(String args[]){

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


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

}
}
Output:
Ajay
Vijay
Ravi
34
8. Lecture Notes
❑ Example Program5
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class LinkedListExample {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new LinkedList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
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

❖ QUIZ:
1. Which of the following class is synchronized?
a. ArrayList
b. Vector
c. LinkedList
d. All of the above
2. In which of the following classes position based operations can be
performed?
a. ArrayList
b. LinkedList
c. Vector
d. All of the above
35
8. Lecture Notes
❑ Difference Between ArrayList and LinkedList

ArrayList LinkedList

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked


array to store the elements. list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList is faster than


is slow because it internally uses an array. If ArrayList because it uses a doubly linked list,
any element is removed from the array, all so no bit shifting is required in memory.
the other elements are shifted in memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

5) The memory location for the elements of The location for the elements of a linked list is
an ArrayList is contiguous. not contagious.

6) Generally, when an ArrayList is initialized, a There is no case of default capacity in a


default capacity of 10 is assigned to the LinkedList. In LinkedList, an empty list is
ArrayList. created when a LinkedList is initialized.

7) To be precise, an ArrayList is a resizable LinkedList implements the doubly linked list of


array. the list interface.

❑ Points to Ponder
❑ Use List Collection classes if the order in which the element added matters
❑ Use List when you want to perform insert, delete and update operations based on
particular positions in the list
❑ ArrayList, LinkedList and Vector all of them implement List interface
❑ LinkedList provides a better performance over ArrayList in insertion and deletion
operation.
❑ In case of frequent insertion and deletion operation, the choice can be LinkedList
than ArrayList
❑ Search operations are faster in ArrayList
❑ Both ArrayList and LinkedList are not synchronized
❑ Vector is synchronized
❑ If thread safety is not important, then we should choose either ArrayList or
LinkedList

36
8. Lecture Notes
1.7. Set Interface
❑ Set Interface in Java is present in java.util package.
❑ Set interface extends from Collection interface
❑ Set is an unordered collection
❑ It doesn’t allow duplicates
❑ If you add duplicates, it will replace the existing one
❑ It allows you to add only a single null value
❑ Implementation classes for Set are TreeSet,HashSet and LinkedHashSet
❑ 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>();
1.8. 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.
❑ No duplicates allowed, unsorted & unordered Set.
❑ 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.
❑ Example Program1
import java.util.*;
class eg {
public static void main(String[] args) {
Set<Integer> s = new HashSet<Integer>();
s.add(1);
O/P: 2 4 1 3 5
s.add(2);
❑ Note: The order of the objects printed are
s.add(3);
not predictable
s.add(4);
s.add(5);
for(Integer i : s)
System.out.print(i + " "); }}
37
8. Lecture Notes
❑ Constructors of Java HashSet class

Sl.
Constructor Description
No.

1) HashSet() It is used to construct a default HashSet.

It is used to initialize the capacity of the hash set to the


2) HashSet(int capacity) given integer value capacity. The capacity grows
automatically as elements are added to the HashSet.

HashSet(int capacity, float It is used to initialize the capacity of the hash set to the
3)
loadFactor) given integer value capacity and the specified load factor.

HashSet(Collection<? extends It is used to initialize the hash set by using the elements
4)
E> c) of the collection c.

❑ Methods of Java HashSet class

Sl. Modifier &


Method Description
No. Type

1) boolean add(E e) It is used to add the specified element to this set if it is not
already present.

2) void clear() It is used to remove all of the elements from the set.

3) object clone() It is used to return a shallow copy of this HashSet instance:


the elements themselves are not cloned.

4) boolean contains(Obj It is used to return true if this set contains the specified
ect o) element.

5) boolean isEmpty() It is used to return true if this set contains no elements.

6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.

7) boolean remove(Obje It is used to remove the specified element from this set if it
ct o) is present.

8) int size() It is used to return the number of elements in the set.

9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator


over the elements in the set.

38
8. Lecture Notes
❑ HashSet example ignoring duplicate elements

import java.util.*;
class HashSet2{
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());
}
}
}
O/P :
Ajay
Vijay
Ravi
❑ HashSet example for removing elements
import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
} 39
8. Lecture Notes
Output:
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

❑ Java HashSet 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 quantity) {
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","Forouzan","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.9. LinkedHashSet
❑ Java LinkedHashSet class contains unique elements only like HashSet.
❑ Java LinkedHashSet class provides all optional set operations and permits null elements.
❑ Java LinkedHashSet class is non-synchronized.
❑ Java LinkedHashSet class maintains insertion order.

40
8. Lecture Notes
❑ Java LinkedHashSet Example
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet<String> set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
} }
Output:
One
Two
Three
Four
Five
❑ Java LinkedHashSet example ignoring duplicate Elements
import java.util.*;
class LinkedHashSet2{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<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 41
Vijay
Ajay
8. Lecture Notes
1.10. TreeSet

❑ No duplicates allowed
❑ Iterates in sorted order
❑ Sorted Collection
❑ By default elements will be in ascending order
❑ Not synchronized
❑ TreeSet implements the Set interface, backed by a TreeMap instance.
❑ This class guarantees that the sorted set will be in ascending element order, sorted according to the
natural order of the elements, or by the comparator provided at set creation time, depending on
which constructor is used.
❑ Example Program1
import java.util.*;
class TreesetEx{
public static void main(String args[]){
TreeSet<String> t1 = new TreeSet<String>(); //create a Treeset object
t1.add("One");
t1.add("Two");
t1.add("Three");
t1.add("Four");
t1.add("Five");
System.out.println("Contents of treeset");
Iterator it1 = t1.iterator(); //obtaining iterator object
while(it1.hasNext()){ // to iterate thru collection.
Object o1=it1.next();
System.out.print(o1+” ”); } } }
Output:
Contents of treeset
Five Four One Three Two
❑ Comparable Interface
❑ This interface can be used to order the user defined objects
❑ It is found in java.lang package
❑ The method found in Comparable interface is
❑ public int compareTo(Object obj)
❑ This method will compare the current object with
42the previous object
8. Lecture Notes
❑ Example using Comparable interface
❑ Sorting Students based on their marks:
❑ Student.java
class Student implements Comparable{
int rollno;
String name;
int marks;
Student(int rollno,String name,int marks){
this.rollno=rollno;
this.name=name;
this.marks=marks;
}
public int compareTo(Object obj){
Student student=(Student)obj;
if(marks==student.marks)
return 0;
else if(marks>student.marks)
return 1;
else
return -1;
}}
❑ Example using Comparable interface
❑ Test.java
import java.util.*;
import java.io.*;
class Test{
public static void main(String args[]){
TreeSet treeset=new TreeSet();
treeset.add(new Student(1,"Ajay",66));
O/P:
treeset.add(new Student(2,"Abhi",96)); 3:Sanjai:45
treeset.add(new Student(3,"Sanjai",45)); 1:Ajay:66
2:Abhi:96
Iterator itr=treeset.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+“:"+st.name+“:"+st.age);
}}} 43
8. Lecture Notes
❖ Quiz
1. Set allows atmost one null element
a. True
b. False

2. Which implementation of Set should we use if we want


the iterator to retrieve the objects in the order we have
inserted?
a. TreeSet
b. HashSet
c. LinkedHashSet

3. If we need to store user defined objects in a TreeSet,


which interface should the corresponding class implement?
a. Set
b. TreeSet
c. Comparable Interface
d. HashSet
❑ 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> c) It is used to add all of the 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 a comparator that arranges elements in
order.
Iterator descendingIterator() It is used to 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, boolean It returns the group of elements that are less than or
inclusive) 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.
44
8. Lecture Notes
Method Description
E higher(E e) It returns the closest greatest element of the specified
element from the set, or null there is no such 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 lie between the given
boolean fromInclusive, E toElement, range.
boolean toInclusive)
SortedSet subSet(E fromElement, E It returns a set of elements that lie between the given
toElement)) 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 are greater than or
boolean inclusive) 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 1:


import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay 45
8. Lecture Notes
❑ Example program1
import java.util.*;
class TreeSet2{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
System.out.println("Traversing element through Iterator in descending order");
Iterator i=set.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output:
Traversing element through Iterator in descending order
Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay
❑ Example program2
import java.util.*;
class TreeSet3{
public static void main(String args[]){
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Lowest Value: "+set.pollFirst());
System.out.println("Highest Value: "+set.pollLast());
} }
Output:
Lowest Value: 12 46
Highest Value: 66
8. Lecture Notes
❑ Example program3
import java.util.*;
class TreeSet4{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");
System.out.println("Initial Set: "+set);

System.out.println("Reverse Set: "+set.descendingSet());

System.out.println("Head Set: "+set.headSet("C", true));

System.out.println("SubSet: "+set.subSet("A", false, "E", true));

System.out.println("TailSet: "+set.tailSet("C", false));


}
}
Output:
Initial Set: [A, B, C, D, E]
Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

❑ Example program4
import java.util.*;
class TreeSet5{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");

System.out.println("Intial Set: "+set);

System.out.println("Head Set: "+set.headSet("C"));

System.out.println("SubSet: "+set.subSet("A", "E"));

System.out.println("TailSet: "+set.tailSet("C"));
}
}
Output:
Intial Set: [A, B, C, D, E]
Head Set: [A, B]
SubSet: [A, B, C, D] 47
TailSet: [C, D, E]
8. Lecture Notes
❑ Example program5

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 quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
// implementing the abstract method
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","Forouzan","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

48
8. Lecture Notes
❑ ClassCast Exception in TreeSet
❑ If we add an object of the class that is not implementing the Comparable interface,
the ClassCast Exception is raised. Observe the following program.
import java.util.*;

class Employee
{

int empId;
String name;

// getting the name of the employee


String getName()
{
return this.name;
}

// setting the name of the employee


void setName(String name)
{
this.name = name;
}

// setting the employee id of the employee


void setId(int a)
{
this.empId = a;
}

// retrieving the employee id of the employee


int getId()
{
return this.empId;
}
}

public class ClassCastExceptionTreeSet


{
// main method
public static void main(String[] argvs)
{
// creating objects of the class Employee
Employee obj1 = new Employee();
Employee obj2 = new Employee();
TreeSet<Employee> ts = new TreeSet<Employee>();
// adding the employee objects to
// the TreeSet class
ts.add(obj1);
ts.add(obj2);
System.out.println("The program has been executed successfully.");
}}
49
8. Lecture Notes
When we compile the above program, we get the ClassCastException, as shown below.
Output:
Exception in thread "main" java.lang.ClassCastException: class Employee cannot be cast to class
java.lang.Comparable (Employee is in unnamed module of loader 'app'; java.lang.Comparable is in
module java.base of loader 'bootstrap')
at java.base/java.util.TreeMap.compare(TreeMap.java:1569)
at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776)
at java.base/java.util.TreeMap.put(TreeMap.java:785)
at java.base/java.util.TreeMap.put(TreeMap.java:534)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at ClassCastExceptionTreeSet.main(ClassCastExceptionTreeSet.java:52)

Explanation: In the above program, it is required to implement a Comparable interface. It is


because the TreeSet maintains the sorting order, and for doing the sorting the comparison of
different objects that are being inserted in the TreeSet is must, which is accomplished by
implementing the Comparable interface.

1.11 Map Interface


❑ Map is an interface that stores data in the form of key value pair
❑ All the keys in the map will be unique
❑ We can retrieve the value stored in a map by providing the key value
❑ A Map cannot contain duplicate values
❑ Each key can map to at most one valueThere are two interfaces for implementing Map in java:
Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap.
❑ 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.
50
8. Lecture Notes
Method Description
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<? It is used to compute a mapping for the specified key
super K,? super V,? extends V> and its current mapped value (or null if there is no
remappingFunction) current mapping).
V computeIfAbsent(K key, It is used to compute its value using the given mapping
Function<? super K,? extends V> function, if the specified key is not already associated
mappingFunction) with a value (or is mapped to null), and enters it into this
map unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and
BiFunction<? super K,? super V,? its current mapped value if the value for the specified
extends V> remappingFunction) key is present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the
value exists within the map, else return false.
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 It performs the given action for each entry in the map
K,? super V> action) until all entries have been processed or the action
throws an exception.
V get(Object key) This method returns the object that contains the value
associated with the key.
V getOrDefault(Object key, V It returns the value to which the specified key is
defaultValue) mapped, or defaultValue if the map contains no mapping
for the key.
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty; returns
false if it contains at least one key.
V merge(K key, V value, If the specified key is not already associated with a value
BiFunction<? super V,? super V,? or is associated with null, associates it with the given
extends V> remappingFunction) non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super It replaces each entry's value with the result of invoking
K,? super V,? extends V> function) the given function on that entry until all entries have
been processed or the function throws an exception.
Collection values() It returns a collection view of the values contained in the
map.
int size() This method returns the number of entries in the map.

51
8. Lecture Notes
❑ Map.Entry 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.

It is used to replace the value corresponding to this


V setValue(V value)
entry with the specified value.

It is used to compare the specified object with the


boolean equals(Object o)
other existing objects.

static <K extends Comparable<? super


It returns a comparator that compare the objects in
K>,V> Comparator<Map.Entry<K,V>>
natural order on key.
comparingByKey()

static <K,V> Comparator<Map.Entry<K,V>>


It returns a comparator that compare the objects by
comparingByKey(Comparator<? super K>
key using the given Comparator.
cmp)

static <K,V extends Comparable<? super


It returns a comparator that compare the objects in
V>> Comparator<Map.Entry<K,V>>
natural order on value.
comparingByValue()

static <K,V> Comparator<Map.Entry<K,V>>


It returns a comparator that compare the objects by
comparingByValue(Comparator<? super V>
value using the given Comparator.
cmp)

❑ Java Map Example: Generic


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 52
101 Vijay
8. Lecture Notes
❑ Java Map Example: comparingByKey()
import java.util.*;
class MapExample3{
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");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey())
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
100=Amit
101=Vijay
102=Rahul
❑ Java Map Example: comparingByKey() in Descending Order
import java.util.*;
class MapExample4{
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");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}

Output:
101=Vijay
102=Rahul
100=Amit

1.12 HashMap
❑ HashMap uses the hashcode value of an object to determine how the object should be stored in
the collection
❑ Hashcode is used again to help locate the object in the collection
❑ Gives you an unsorted and unordered Map
❑ Allows one null key and multiple null values in a collection
❑ HashMap are not synchronized 53
8. Lecture Notes
❑ Map is an object that stores key/value pairs. Given a key, you can find its value.
❑ Keys must be unique, but values may be duplicated.
❑ The HashMap class provides the primary implementation of the map interface.
❑ The HashMap class uses a hash table to implement Map interface.
❑ This allows the execution time of basic operations, such as get() and put() to be constant.
❑ Example Program1
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap<String,Double> hm = new
HashMap<String,Double>();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Tod Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
The output of the program is
// Get a set of the entries
Ralph Smith: -19.08
Set set = hm.entrySet();
Tom Smith: 123.22
// Get an iterator
John Doe: 3434.34
Iterator i = set.iterator();
Tod Hall: 99.22
// Display elements
Jane Baker: 1378.0
while(i.hasNext()) {
John Doe's new balance: 4434.34
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + ": "+ me.getValue()); }
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe")); } }

54
8. Lecture Notes
❑ No Duplicate Key on HashMap
import java.util.*;
public class HashMapExample2{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(1,"Grapes"); //trying duplicate key

System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana

❑ Java HashMap example to add() elements

import java.util.*;
class HashMap1{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
System.out.println("Initial list of elements: "+hm);
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

System.out.println("After invoking put() method ");


for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}

hm.putIfAbsent(103, "Gaurav");
System.out.println("After invoking putIfAbsent() method ");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
55
8. Lecture Notes
Output:
Initial list of elements: {}
After invoking put() method
100 Amit
101 Vijay
102 Rahul
After invoking putIfAbsent() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
After invoking putAll() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
❑ Java HashMap example to remove() elements
import java.util.*;
public class HashMap2 {
public static void main(String args[]) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(103, "Gaurav");
System.out.println("Initial list of elements: "+map);
//key-based removal
map.remove(100);
System.out.println("Updated list of elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Updated list of elements: "+map);
//key-value pair based removal
map.remove(102, "Rahul");
System.out.println("Updated list of elements: "+map);
}
}
Output:
Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {102=Rahul, 103=Gaurav}
Updated list of elements: {103=Gaurav}

❑ Java HashMap example to replace() elements


import java.util.*;
class HashMap3{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
56
hm.put(102,"Rahul");
8. Lecture Notes
System.out.println("Initial list of elements:");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(102, "Gaurav");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(101, "Vijay", "Ravi");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replaceAll((k,v) -> "Ajay");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay
❑ Java HashMap 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 quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher; 57
this.quantity = quantity; } }
8. Lecture Notes
public class MapExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new HashMap<Integer,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(1,b1);
map.put(2,b2);
map.put(3,b3);

//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications and Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6

1.13. LinkedHashMap

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

58
8. Lecture Notes
❑ Java LinkedHashMap Example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){

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

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
❑ Java LinkedHashMap Example: Key-Value pair
import java.util.*;
class LinkedHashMap2{
public static void main(String args[]){
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Fetching key
System.out.println("Keys: "+map.keySet());
//Fetching value
System.out.println("Values: "+map.values());
//Fetching key-value pair
System.out.println("Key-Value pairs: "+map.entrySet());
}
}
Output:
Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]

❑ Java LinkedHashMap Example:remove()


import java.util.*;
public class LinkedHashMap3 {
public static void main(String args[]) {
Map<Integer,String> map=new LinkedHashMap<Integer,String>();
map.put(101,"Amit");
map.put(102,"Vijay");
map.put(103,"Rahul");
System.out.println("Before invoking remove() method: "+map);
map.remove(102);
System.out.println("After invoking remove() method: "+map);
59
}
}
8. Lecture Notes
❑ Output:
Before invoking remove() method: {101=Amit, 102=Vijay, 103=Rahul}
After invoking remove() method: {101=Amit, 103=Rahul}
❑ Java LinkedHashMap 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 quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class MapExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(2,b2);
map.put(1,b1);
map.put(3,b3);

//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}

Output:
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6

60
8. Lecture Notes
❑ The Hashtable Class
❑ Part of java.util package
❑ It implements Map interface and extends Dictionary Class
❑ It can contain only unique elements
❑ The key cannot have a null value
❑ It is a synchronized class
❑Hashtable Example Program
import java.util.*;
class HashTableDemo {
public static void main(String args[]) {
// Create a hash map
Hashtable<String,Double> balance = new Hashtable<String,Double>();
Enumeration names;
String str;
double bal;
balance.put("Arun", new Double(3434.34));
balance.put("Radha", new Double(123.22));
balance.put("Ram", new Double(99.22));
// Show all balances in hash table.
names = balance.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " +
balance.get(str)); }
System.out.println(); } }

1.14. TreeMap:
❑ Implements Map interface
❑ Provides efficient means of storing key/value pairs in sorted order
❑ Allows rapid retrieval
❑ Guarantees that its elements will be sorted in ascending key order
❑ The Key cannot be null but it can contain multiple null values

61
8. Lecture Notes
❑ TreeMap Example Program
import java.util.*;
class TreeMapDemo{
public static void main(String arg[]){
TreeMap tm = new TreeMap();
tm.put("Suresh",new Double(15357.75));
tm.put("Meenu",new Float(18345.50));
tm.put("Viren",new Integer(20000));
tm.put("Avinash",new Double(19900.25));
tm.put("Priya",new Integer(12000));
tm.put("Zakir",new Float(16500.90));
tm.put("Nirav",new Double(22000));
tm.put("Jayesh",new Integer(15000));
tm.put("Poorva","Zero");
Set salary = tm.entrySet();
Iterator it = salary.iterator();
while(it.hasNext()){
Map.Entry e = (Map.Entry) it.next();
System.out.println(e.getKey()+" : "+" is "+e.getValue());
}}}
❑ Properties
❑ Extends Hashtable.
❑ Used to maintain lists of key value pairs in which both the key and the value are Strings
❑ Useful method
❑ //Used to print all the system properties
Properties p=System.getProperties();
p.list(System.out);
❑ //Used to get a system property user.name
System.out.println(p.getProperty("user.name"));
❑ Example Program
import java.util.*;
class mysysproperties
{
public static void main(String arg[])
{
Properties p=System.getProperties();
p.list(System.out);
System.out.println(p.getProperty("user.name"));
}
} 62
8. Lecture Notes
❑ Quiz

1. TreeSet map = new TreeSet();


map.add("one");
map.add("two");
map.add("three");
map.add("one");
map.add("four");
Iterator it = map.iterator();
while (it.hasNext() ) {
System.out.print( it.next() + " " );
}
A. Compilation fails
B. four three two one
C. one two three four
D. four one three two

2. public static void before() {


Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}
Which of the following statements are true?
A. The before() method will print 1 2
B. The before() method will print 1 2 3
C. The before() method will not compile.
D. The before() method will throw an exception at runtime.

63
8. Lecture Notes
❖ Quiz

1. TreeSet map = new TreeSet();


map.add("one");
map.add("two");
map.add("three");
map.add("one");
map.add("four");
Iterator it = map.iterator();
while (it.hasNext() ) {
System.out.print( it.next() + " " );
}

A. Compilation fails
B. four three two one
C. one two three four
D. four one three two

2. public static void before() {


Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}

Which of the following statements are true?


A. The before() method will print 1 2
B. The before() method will print 1 2 3
C. The before() method will not compile.
D. The before() method will throw an exception at runtime.

1.15. Queue Interface:

❑ The interface Queue is available in the java.util package and does extend the Collection interface.
It is used to keep the elements that are processed in the First In First Out (FIFO) manner.
❑ It is an ordered list of objects, where insertion of elements occurs at the end of the list, and
removal of elements occur at the beginning of the list.
❑ Being an interface, the queue requires, for the declaration, a concrete class, and the most
common classes are the LinkedList and PriorityQueue in Java.
❑ Implementations done by these classes are not thread safe. If it is required to have a thread safe
implementation, PriorityBlockingQueue is an available option.

64
8. Lecture Notes
❑ Methods of Java Queue Interface

Method Description

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

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

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

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

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head
of this queue, or returns null if this queue is empty.

❑ Features of a Queue
❑ As discussed earlier, FIFO concept is used for insertion and deletion of elements from a
queue.
❑ The Java Queue provides support for all of the methods of the Collection interface
including deletion, insertion, etc.
❑ PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are used
most frequently.
❑ The NullPointerException is raised, if any null operation is done on the BlockingQueues.
❑ Those Queues that are present in the util package are known as Unbounded Queues.
❑ Those Queues that are present in the util.concurrent package are known as bounded
Queues.
❑ All Queues barring the Deques facilitates removal and insertion at the head and tail of the
queue; respectively. In fact, deques support element insertion and removal at both ends.
1.16. PriorityQueue:
❑ PriorityQueue is also class that is defined in the collection framework that gives us a way for
processing the objects on the basis of priority.
❑ It is already described that the insertion and deletion of objects follows FIFO pattern in the Java
queue.
❑ However, sometimes the elements of the queue are needed to be processed according to the
priority, that's where a PriorityQueue comes into action.

65
8. Lecture Notes
❑ 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 66
Vijay
8. Lecture Notes
1.17. Deque Interface

❑ The interface called Deque is present in java.util package.


❑ It is the subtype of the interface queue.
❑ The Deque supports the addition as well as the removal of elements from both ends of the data
structure.
❑ Therefore, a deque can be used as a stack or a queue. We know that the stack supports the Last In
First Out (LIFO) operation, and the operation First In First Out is supported by a queue. As a deque
supports both, either of the mentioned operations can be performed on it. Deque is an acronym
for "double ended queue".
❑ Methods of Java Deque Interface

Method Description
boolean add(object) It is used to insert the specified element into this deque and return true
upon success.
boolean offer(object) It is used to insert the specified element into this deque.
Object remove() It is used to retrieve and removes the head of this deque.
Object poll() It is used to retrieve and removes the head of this deque, or returns null
if this deque is empty.
Object element() It is used to retrieve, but does not remove, the head of this deque.
Object peek() It is used to retrieve, but does not remove, the head of this deque, or
returns null if this deque is empty.
Object peekFirst() The method returns the head element of the deque. The method does
not remove any element from the deque. Null is returned by this
method, when the deque is empty.
Object peekLast() The method returns the last element of the deque. The method does not
remove any element from the deque. Null is returned by this method,
when the deque is empty.
Boolean offerFirst(e) Inserts the element e at the front of the queue. If the insertion is
successful, true is returned; otherwise, false.
Object offerLast(e) Inserts the element e at the tail of the queue. If the insertion is
successful, true is returned; otherwise, false.

❑ ArrayDeque class
❑ it is not possible to create an object of an interface in Java. Therefore, for instantiation, a
class that implements the Deque interface is required and that class is ArrayDeque.

67
8. Lecture Notes
❑ Unlike Queue, we can add or remove elements from both sides.
❑ Null elements are not allowed in the ArrayDeque.
❑ ArrayDeque is not thread safe, in the absence of external synchronization.
❑ ArrayDeque has no capacity restrictions.
❑ ArrayDeque is faster than LinkedList and Stack.
❑ Java ArrayDeque Example
import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Ravi
Vijay
Ajay

❑ Java ArrayDeque Example: offerFirst() and pollLast()


import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
68
System.out.println("After offerFirst Traversal...");
8. Lecture Notes
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Output:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
Vimal
❑ 1.18. Utility Classes
❑ A utility class in Java is a class that provides static methods that are accessible for use across an
application. The static methods in utility classes are used for performing common routines in our
application.
❑ Utility classes cannot be instantiated and are sometimes stateless without static variables. We
declare a utility class as final, and all its methods must be static.
❑ Since we don’t want our utility classes to be instantiated, a private constructor is introduced.
Having a private constructor means that Java won’t create a default constructor for our utility
class. The constructor can be empty.
❑ The purpose of a utility class is to provide methods for executing certain functionalities within a
program, while the main class focuses on the core problem it solves.
❑ Methods of a utility are accessed via the class name. It makes our code more flexible for use
while remaining modular.
69
8. Lecture Notes
❑ Java has utility classes such as java.util.Arrays, java.lang.Math, java.util.Scanner,
java.util.Collections, etc.

❑ How to Create a Java Utility Class

❑ Creating a utility class is not so different from how we create a helper class. A few things are done
a little differently when creating a utility class.

❑ To create a utility class, we use a public access modifier and also declare the class as final. The
final keyword used when creating utility classes means that the class would remain unchangeable.
It cannot be inherited or instantiated.

❑ Program to create Utility Class

public final class MyUtilityClass {


private MyUtilityClass(){}
public static String returnUpperCase(String stringInput) {
return stringInput.toUpperCase();
}
public static String returnLowerCase(String stringInput) {
return stringInput.toLowerCase();
}
public static String[] splitStringInput(String stringInput, String delimiter) {
return stringInput.split(delimiter);
}
}

❑ Another rule to observe is that all methods of a utility class are static, with a public access
modifier.

❑ Since we have only static methods within utility classes, these methods can only be accessed via
the class name

70
9. Assignment - I

1. Write a Java program that creates an ArrayList of integers, adds elements to it, removes

elements, and then prints out each element in the list using a for-each loop.

Test Cases:

❑ Create an ArrayList, add integers 1, 2, 3, 4, 5.

❑ Check that the size of the list is 5 after adding.

❑ Remove the element at index 2.

❑ Verify that the element removed is 3 and the size of the list is now 4.

❑ Print all elements in the list and ensure they are in the correct order.

2. Implement a Java program that uses a HashMap to store employee IDs (as keys) and their

corresponding names (as values). Allow the user to add new entries, remove existing ones by ID,

and display all entries in the HashMap.

Test Cases:

❑ Add entries for employee IDs 101, 102, and 103 with names John, Jane, and Jake

respectively. Check that the HashMap contains these entries.

❑ Remove the entry with ID 102.

❑ Verify that the HashMap no longer contains this ID.

❑ Display all entries in the HashMap and ensure they are displayed correctly.

71
9. Assignment - II

1. Write a Java program that demonstrates the use of an Iterator to iterate through and print out

elements in a LinkedList of strings. Allow the user to add elements to the LinkedList interactively.

Test Cases:

❑ Add strings "apple", "banana", "cherry" to the LinkedList.

❑ Ensure all elements are added correctly.

❑ Use an Iterator to print all elements in the LinkedList and verify they are printed in

the correct order.

❑ Add a new string "orange" and verify it appears correctly when iterating through the

LinkedList again.

2. Implement a Java program that prompts the user to enter a list of integers into an ArrayList. Sort

the ArrayList in descending order using Collections.sort() and a custom Comparator. Print the

sorted list.

Test Cases:

❑ Enter integers 5, 3, 9, 1, 7 into the ArrayList.

❑ Ensure they are added in the correct order.

❑ Sort the ArrayList and verify the order is now 9, 7, 5, 3, 1.

❑ Sort an empty ArrayList and verify it remains empty after sorting.

72
9. Assignment - III

1. Create a Java program that reads a paragraph of text from the user and stores each word in a

HashSet. Output the unique words in alphabetical order.

Test Cases:

❑ Enter the text "apple banana cherry banana apple" and verify the HashSet contains

only unique words.

❑ Output the unique words and ensure they are displayed in alphabetical order.

❑ Enter an empty paragraph and verify the HashSet and output are empty.

2. Write a generic method in Java that takes an ArrayList of any type and returns the maximum

element in the list. Test the method with different types such as Integer, Double, and String.

Test Cases:

❑ Create an ArrayList of integers containing 3, 7, 2, 9.

❑ Verify the maximum element returned is 9.

❑ Create an ArrayList of doubles containing 4.5, 6.1, 3.8.

❑ Verify the maximum element returned is 6.1.Create an ArrayList of strings containing

"apple", "banana", "cherry". Verify the maximum element returned is "cherry".

73
9. Assignment - IV

1. Develop a multithreaded Java application that uses a ConcurrentHashMap to store real-time

sensor data from multiple sensors. Implement threads to read and write data to the

ConcurrentHashMap safely.

Test Cases:

❑ Simulate concurrent reads and writes from multiple threads to the

ConcurrentHashMap.

❑ Ensure data integrity by verifying that all sensor readings are correctly stored and

retrieved.

❑ Test the application with various numbers of threads and sensor inputs to ensure

thread safety.

2. Design and implement a custom Collection class in Java that behaves like a queue (FIFO). Include

methods for enqueue, dequeue, and size management. Test the class with various types of data.

Test Cases:

❑ Enqueue integers 1, 2, 3 into the custom queue.

❑ Verify they are dequeued in the correct order (1, 2, 3).

❑ Enqueue strings "apple", "banana", "cherry".

❑ Verify they are dequeued in the correct order ("apple", "banana", "cherry").

❑ Test edge cases such as dequeueing from an empty queue and verify appropriate

exceptions are thrown.

74
9. Assignment - V

1. Create a Java program that measures and compares the performance of adding, searching, and

removing elements in ArrayList, LinkedList, HashSet, and TreeMap. Use large datasets and report

the findings with benchmarks.

Test Cases:

❑ Measure the time taken to add a large number of elements to each collection type and

compare the results.

❑ Search for an element in each collection type and verify the search time.

❑ Remove elements from each collection type and measure the removal time, ensuring

consistent benchmarking across different operations.

2. Implement a Java program that benchmarks the performance (time complexity) of various

operations (add, remove, search) for ArrayList, LinkedList, HashSet, and TreeMap. Use Big-O

notation to analyze and justify your results.

Test Cases:

❑ Perform operations on each collection type with varying numbers of elements (e.g., 1000,

10000, 100000).

❑ Measure and record the time taken for each operation and plot graphs to visualize the

performance differences.

❑ Validate the theoretical time complexities (e.g., O(1), O(n), O(log n)) with the measured

results.

75
10. Part A Questions & Answers
1. What is a Collection in Java? CO1, K1
A Collection in Java is an object that groups multiple elements into a single unit.
2. Name two types of collections in Java. CO1, K1
ArrayList and HashMap.
3. What interface does ArrayList implement in Java? CO1, K1
ArrayList implements the List interface.
4. What does the term "generic" mean in Java collections? CO1, K1
Generics allow the type of elements in a collection to be specified when defining the
collection.
5. Explain the difference between ArrayList and LinkedList. CO1, K1
ArrayList uses a dynamic array for storing elements, while LinkedList uses a doubly
linked list.
6. What is the primary advantage of using a HashSet in Java? CO1, K1
HashSet provides constant-time performance for basic operations like add, remove,
contains.
7. Which interface in Java collections allows duplicate elements? CO1, K1
List interface allows duplicate elements.
8. How are elements stored in a TreeMap in Java? CO1, K1
Elements in a TreeMap are stored in a sorted order defined by the natural order of
its keys
or a Comparator.
9. What is the purpose of the Iterator interface in Java collections? CO1, K1
Iterator allows traversing through elements in a collection sequentially.
10. What is the difference between HashSet and TreeSet in Java? CO1, K1
HashSet does not maintain elements in any specific order, while TreeSet stores elements
in sorted order.
11. Describe the main advantage of using a LinkedHashMap over a HashMap. CO1, K2
LinkedHashMap maintains insertion order of elements, whereas HashMap does not guarantee any
specific order.
12. How can you synchronize an ArrayList in Java? CO1, K2
Use Collections.synchronizedList() method to create a synchronized (thread-safe)
ArrayList.
13. Explain the purpose of the Queue interface in Java collections. CO1, K2
Queue interface represents a collection
76 designed for holding elements before
processing (FIFO order).
10. Part A Questions & Answers
14. What is the purpose of the LinkedHashMap class in Java? CO1,K2
LinkedHashMap extends HashMap to maintain insertion order of elements, along with
optional access order.
15. What is the difference between poll() and remove() methods in Queue interface?
CO1, K1
poll() method retrieves and removes the head of the Queue, returning null if
empty; remove() does the same but throws NoSuchElementException if empty.
16. What does the term "capacity" refer to in ArrayList in Java? CO1, K1
Capacity refers to the size of the internal array used to store elements in ArrayList.
17. Explain the purpose of the Set interface in Java collections. CO1,K1
Set interface represents a collection that does not allow duplicate elements.
18. How does a HashSet ensure uniqueness of elements in Java? CO1,K1
HashSet uses hash codes of elements to ensure uniqueness and determines equality
using the equals() method.
19. Describe the purpose of the Deque interface in Java collections. CO1, K1
Deque interface represents a double-ended queue that allows insertion and removal
of elements at both ends.
20. What is the advantage of using TreeSet over HashSet in Java? CO1, K2
TreeSet maintains elements in a sorted order defined by either natural order or a
Comparator, whereas HashSet does not maintain any order.
21. Explain the purpose of the Map interface in Java collections. CO1, K2
Map interface represents a collection of key-value pairs where each key is unique.
22. What does the term "concurrent" mean in ConcurrentHashMap in Java? CO1, K2
ConcurrentHashMap allows multiple threads to modify the map concurrently without
causing any inconsistency.
23. Describe the difference between HashMap and Hashtable in Java. CO1, K2
HashMap is not synchronized and allows null values, while Hashtable is synchronized
and does not allow null keys or values.
24. How can you obtain a synchronized view of a Map in Java? CO1, K2
Use Collections.synchronizedMap() method to create a synchronized (thread-safe) Map.
25. Explain the purpose of the Collections class in Java. CO1, K2
The Collections class provides utility methods (like sorting and searching) for
operating on collections.
77
11. Part B Questions
1. Write a Java program that implements an ArrayList to store and manage student names
and their corresponding grades. Include methods to add new entries, remove entries by
student name, and calculate the average grade of all students. (CO6, K6)
2. Develop a Java program that uses a HashMap to manage a phone book. The program
should allow users to add new contacts, search for contacts by name, and display all
contacts in alphabetical order. (CO6, K6)
3. Create a Java program that simulates a queue management system for a service center.
Use LinkedList as the underlying data structure. Implement methods to enqueue
customers, dequeue customers, and display the current queue status. (CO6, K6)
4. Write a Java program that uses TreeSet to manage a collection of employee objects. Each
employee should have attributes such as ID, name, and salary. Implement methods to add
new employees, remove employees by ID, and search employees by name. (CO6, K6)
5. Develop a multithreaded Java application that uses ConcurrentHashMap to store and
manage real-time sensor data from multiple sensors. Implement threads to simulate data
generation and retrieval operations. (CO6, K6)
6. Implement a Java program that simulates a stack using LinkedList. Include methods to
push elements onto the stack, pop elements from the stack, and peek at the top element
without removing it. (CO6, K6)
7. Develop a Java program that uses PriorityQueue to manage a list of tasks. Each task
should have a priority and a description. Implement methods to add new tasks with
priorities, retrieve and process tasks based on priority. (CO6, K6)
8. Write a Java program that demonstrates the use of BlockingQueue for implementing a
producer-consumer scenario. Use LinkedBlockingQueue to handle messages between
producers and consumers. (CO6, K6)
9. Develop a Java program that uses LinkedHashSet to manage a collection of unique
transaction IDs. Implement methods to add new transactions, remove transactions, and
display all transactions in the order of their insertion. (CO6, K6)
10. Write a Java program that utilizes BiMap from the Guava library to manage a bidirectional
map between student IDs and names. Implement methods to add new mappings, retrieve
values by keys, and retrieve keys by values. (CO6, K6)

78
12. Supportive Online Certifications

1. Java Programming: Complete Beginner to Advanced https://www.udemy.com/course/java-


programming-complete-beginner-to- advanced/(Paid)

2. Java DeveloperCertification (Infosys Springboard):


https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_01319338454
0020736264_shared/overview

3. Java Programming Masterclass updated to Java 17: https://www.udemy.com/course/java-


the-complete-java-developer-course/ (Paid)

4. Programming in Java: https://nptel.ac.in/courses/106/105/106105191/ (Paid)

5. Java Learning Subscription: https://education.oracle.com/java-se-8-


fundamentals/courP_3348 (Paid)

79
13. Real Time Applications

❖ Desktop GUI Programs

❖ Mobile Applications

❖ Artificial intelligence

❖ Web based Applications

❖ Big data technology

❖ Gaming Applications

❖ Business Applications

❖ Embedded Systems

❖ Cloud based Applications

❖ Scientific Applications

❖ Distributed Applications

❖ Web servers and Application servers

❖ Software Tools

80
14. Contents Beyond the Syllabus
❖ EnumSet in Java
The EnumSet class of the Java collections framework provides a set implementation of
elements of a single enum. Before you learn about EnumSet, make sure to know about Java
Enums. It implements the Set interface.

Key characteristics and features of EnumSet:

1.Creation: Can create an EnumSet using several static factory methods.


The most common ways are EnumSet.noneOf(EnumType.class) to create an empty set,
EnumSet.allOf(EnumType.class) to create a set containing all enum constants, or
EnumSet.of(EnumType.const1, EnumType.const2, ...) to create a set containing specific enum
constants.

2.Type-Safe:EnumSet is type-safe, meaning you can only add elements of the same
enum type to the set. Attempting to add elements of different enum types will result in a
compilation error.
3.Efficient Storage: EnumSet internally uses bit vectors (bitsets) to efficiently
represent the set of enum constants. This makes it very memory-efficient, especially
when dealing with large enums.
4.Performance: EnumSet provides very fast set operations (union, intersection,
difference, etc.) due to its optimized internal representation.

Using allOf(Size):
The allof() method creates an enum set that contains all the values of the specified
enum type Size. For example,

81
14. Contents Beyond the Syllabus
import java.util.EnumSet;

class Main

{
// an enum named Size
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
public static void main(String[] args) {
// Creating an EnumSet using allOf()
EnumSet<Size> sizes = EnumSet.allOf(Size.class);
System.out.println("EnumSet: " + sizes);

}
}
Output
EnumSet: [SMALL, MEDIUM, LARGE, EXTRALARGE]

Using noneOf(Size)
The noneOf() method creates an empty enum set. For example,
import java.util.EnumSet;

class Main
{
// an enum type Size
enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE


}
public static void main(String[] args) {
// Creating an EnumSet using noneOf()
EnumSet<Size> sizes = EnumSet.noneOf(Size.class); System.out.println("Empty EnumSet: " +
sizes);

}
}
Output
Empty EnumSet : []
82
14. Contents Beyond the Syllabus
Using of() Method

The of() method creates an enum set containing the specified elements. For example,

import java.util.EnumSet;

class Main

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE }

public static void main(String[] args) {

// Using of() with a single parameter

EnumSet<Size> sizes1 = EnumSet.of(Size.MEDIUM);

System.out.println("EnumSet1: " + sizes1);


EnumSet<Size> sizes2 = EnumSet.of(Size.SMALL, Size.LARGE);
System.out.println("EnumSet2: " + sizes2); }

}
Output
EnumSet1: [MEDIUM] EnumSet2: [SMALL, LARGE]

Methods of EnumSet

add() - inserts specified enum values to the enum set


addAll()- inserts all the elements of the specified collection to the set hasNext()- returns true
if there is a next element in the enum set next() -returns the next element in the enum set

remove() - removes the specified element from the enum set

removeAll() - removes all the elements from the enum set

83
15. Assessment Schedule
Tentative schedule for the Assessment During 2024-2025 Odd Semester

S. Name of the
Start Date End Date Portion
No. Assessment

As Per Academic As Per Academic


1 Unit Test 1 Unit 1
Schedule Schedule

As Per Academic As Per Academic


2 FIAT Unit 1 & 2
Schedule Schedule
As Per Academic As Per Academic
3 Unit Test 2 Unit 3
Schedule Schedule
As Per Academic As Per Academic
4 SIAT Unit 3 & 4
Schedule Schedule
As Per Academic As Per Academic
5 Revision 1 Unit 5, 1 & 2
Schedule Schedule
As Per Academic As Per Academic
6 Revision 2 Unit 3 & 4
Schedule Schedule
As Per Academic As Per Academic
7 Model All 5 Units
Schedule Schedule

84
16. Prescribed Text Books
&
Reference Books
TEXT BOOK:
1. Cay S. Horstmann, "Core Java Volume I--Fundamentals,"
12th Edition, 2019.
2. Joshua Bloch, "Effective Java," 3rd Edition, 2018.
3. Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams,
and Functional-Style Programming," 1st Edition, 2014.
4. Herbert Schildt, "Java: The Complete Reference," 11th
Edition, 2018.
5. Alan Mycroft and Martin Odersky, "Programming in Scala,"
4th Edition, 2020.
REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition,
2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional
Programming," 1st Edition, 2014.

85
17. Mini Project - I
Employee Register
You need to maintain the details of all employees of an Organization.
The following details of the employee needs to be maintained
First Name
Last Name
Mobile Number
Email
Address
There is no higher limit to store the number of employee in our application. Get the number of
employees first before getting all the employee details.
Collect all employee details and store them in an appropriate collection type, so that when the
collection is printed, it prints the employee details sorted by their first name.
Use Generics.
Note:
In case of Java, Use Java Format Specifier:
System.out.format("%-15s %-15s %-15s %-30s %-
15s\n","Firstname","Lastname","Mobile","Email","Address");
Sample Output:
Enter the Number of Employees
2
Enter Employee 1 Details:
Enter the Firstname
Janani
Enter the Lastname
Velmurugan
Enter the Mobile
7890123
Enter the Email
[email protected]
Enter the Address
Chennai
Employee List:
FirstName SecondName MobileNumber Email Address
Anitha Ramesh 9906699224 [email protected] Bangalore
Janani Velmurugan 7890123000 [email protected] Chennai 86
17. Mini Project - II
Operations on String List

Write a Program to perform the basic operations like insert, delete, display and search in list. List
contains
String object items where these operations are to be performed.
Sample Input and Output :
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
1
Enter the item to be inserted:
Bottle
Inserted successfully
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
1
Enter the item to be inserted:
Water
Inserted successfully
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
1
Enter the item to be inserted:
Cap
Inserted successfully
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
1
Enter the item to be inserted:
Monitor
Inserted successfully
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice : 87
2
17. Mini Project - II
Enter the item to search :
Mouse
Item not found in the list.
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
2
Enter the item to search :
Monitor
Item found in the list.
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
3
Enter the item to delete :
Mouse
Item does not exist.
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
4
The Items in the list are :
Bottle
Water
Cap
Monitor
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
3
Enter the item to delete :
Cap
Deleted successfully
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
4 88
17. Mini Project - II
The Items in the list are :
Bottle
Water
Monitor
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice :
5

89
17. Mini Project - III
Collect Unique Symbols From Set of Cards

Playing cards during travel is a fun filled experience. For this game they wanted to collect all four
unique symbols. Can you help these guys to collect unique symbols from a set of cards?
Create Card class with attributes symbol and number. From our main method collect each card
details (symbol and number) from the user.

Collect all these cards in a set, since set is used to store unique values or objects.
Once we collect all four different symbols display the first occurrence of card details in alphabetical
order.

Sample input output


Enter a card :
a
1
Enter a card :
a
2
Enter a card :
a
7
Enter a card :
d
6
Enter a card :
c
2
Enter a card :
d
1
Enter a card :
c
1
Enter a card :
b
2
Four symbols gathered in 8 cards.
Cards in Set are :
a1
b2
c2
d6

90
17. Mini Project - IV
Collect and Group Cards

Write a program to collect and store all the cards to assist the users in finding all the cards in a given
symbol.
This cards game consist of N number of cards. Get N number of cards details from the user and
store
the values in Card object with the attributes symbol and number.
Store all the cards in a map with symbol as its key and list of cards as its value. Map is used here to
easily group all the cards based on their symbol.
Once all the details are captured print all the distinct symbols in alphabetical order from the Map. For
each symbol print all the card details, number of cards and their sum respectively.

Sample input output :


Enter Number of Cards :
13
Enter card 1:
s
1
Enter card 2:
s
12
Enter card 3:
s
13
Enter card 4:
d
4
Enter card 5:
c
5
Enter card 6:
h
5
Enter card 7:
h
7
Enter card 8:
c
3
Enter card 9:
c
2

91
17. Mini Project - IV
Enter card 10:
h
9
Enter card 11:
s
7
Enter card 12:
d
4
Enter card 13:
d
3
Distinct Symbols are :
cdhs
Cards in c Symbol
c5
c3
c2
Number of cards : 3
Sum of Numbers : 10
Cards in d Symbol
d4
d4
d3
Number of cards : 3
Sum of Numbers : 11
Cards in h Symbol
h5
h7
h9
Number of cards : 3
Sum of Numbers : 21
Cards in s Symbol
s1
s 12
s 13
s7
Number of cards : 4
Sum of Numbers : 33

92
17. Mini Project - V
Set of Boxes

Problem Statement:
Write a Program to insert the box details into the set.
Problem Constraints:
Create a Box Class and its attributes are length (Double), width (Double) and height (Double).
Get the Box details from the user and insert it to the Set.
We need to store the details of boxes with different volumes. When the volume of a new box is the
same as the volumes of a previous box included in the Set, dont insert this box in the Set.
The Box is said to be same when their volumes are the equal.
Override the equals method to compare the box volumes.
Sample Input and Output :
Enter the number of Box
5
Enter the Box 1 details
Enter Length
2.1
Enter Width
1.2
Enter Height
2.1
Enter the Box 2 details
Enter Length
3.2
Enter Width
2.3
Enter Height
3.2
Enter the Box 3 details
Enter Length
1.2
Enter Width
2.1
Enter Height
1.2
Enter the Box 4 details
Enter Length
3.2
Enter Width
2.3
Enter Height
3.2

93
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document through
email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute, or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system.
If you are not the intended recipient you are notified that disclosing, copying,
distributing, or taking any action in reliance on the contents of this information is strictly
prohibited.

90

You might also like