22CS305- AJP UNIT1
22CS305- AJP UNIT1
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
11 Part B Questions 78
13 Real-Time Applications 80
15 Assessment Schedule 84
5
1. Course Objectives
OBJECTIVES: ( To be updated )
❖ Gain a comprehensive understanding of the Java Collections Framework and its various
❖ 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
❖ Understand advanced Stream API features and gain proficiency in using regular expressions
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.
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
10
4. Course Outcomes
At the end of this course, the students will be able to:
CO5 Effectively use regular expressions for advanced text processing tasks. 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
➢ 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
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:
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.
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.
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
boolean contains(Object o) It returns true if the list contains the specified element.
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.
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.
void sort(Comparator<? super It is used to sort the elements of the list on the basis of the
E> c) specified comparator.
int size() It is used to return the number of elements present in the list.
}
}
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:
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{
❑ 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
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;
❑ 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:
❑ Example Program4
import java.util.*;
public class LinkedList3 {
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[]){
}
}
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
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.
❑ 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.
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.
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.
4) boolean contains(Obj It is used to return true if this set contains the specified
ect o) element.
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.
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: []
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
❑ 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("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;
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.
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
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
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");
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}
//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[]){
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]
//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
63
8. Lecture Notes
❖ Quiz
A. Compilation fails
B. four three two one
C. one two three four
D. four one three two
❑ 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
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
❑ 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.
❑ 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:
❑ 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,
Test Cases:
❑ Add entries for employee IDs 101, 102, and 103 with names John, Jane, and Jake
❑ 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:
❑ Use an Iterator to print all elements in the LinkedList and verify they are printed in
❑ 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:
72
9. Assignment - III
1. Create a Java program that reads a paragraph of text from the user and stores each word in a
Test Cases:
❑ Enter the text "apple banana cherry banana apple" and verify the HashSet contains
❑ 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:
73
9. Assignment - IV
sensor data from multiple sensors. Implement threads to read and write data to the
ConcurrentHashMap safely.
Test Cases:
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:
❑ Verify they are dequeued in the correct order ("apple", "banana", "cherry").
❑ Test edge cases such as dequeueing from an empty queue and verify appropriate
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
Test Cases:
❑ Measure the time taken to add a large number of elements to each collection type and
❑ 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
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
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
79
13. Real Time Applications
❖ Mobile Applications
❖ Artificial intelligence
❖ Gaming Applications
❖ Business Applications
❖ Embedded Systems
❖ Scientific Applications
❖ Distributed Applications
❖ 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.
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 {
}
}
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 {
}
Output
EnumSet1: [MEDIUM] EnumSet2: [SMALL, LARGE]
Methods of EnumSet
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
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.
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.
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