20CS305 Advance Java Programming Unit 1.ppt

logesswarisrinivasan 32 views 165 slides Oct 11, 2024
Slide 1
Slide 1 of 165
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165

About This Presentation

JAVA


Slide Content

22CS305
ADVANCED JAVA PROGRAMMING
R.M.K. ENGINEERING COLLEGE
(AN AUTONOMOUS INSTITUTION)
R.S.M. Nagar, Kavaraipettai, Gummidipoondi Taluk, Tiruvallur District – 601206.
(Affiliated to Anna University, Chennai/Approved by AICTE, New Delhi/ ISO 21001:2018 Certified Institution/
Accredited by NAAC with A+ Grade/ All eligible UG Programs are accredited by NBA, New Delhi)
1
UNIT 1 – COLLECTIONS FRAMEWORK AND UTILITY CLASSES

Reinforcement Learning 2
UNIT – I
COLLECTIONS FRAMEWORK AND UTILITY CLASSES
Introduction to Collections Framework
Collection Interface
Methods in Collection Interface
Iterable and Iterator Interfaces
List Interface - ArrayList - LinkedList
Set Interface – HashSet - Linked Hash Set - Tree Set
Map Interface - HashMap – LinkedHashMap –
TreeMap
Queue Interface – PriorityQueue
Deque Interface
Utility Classes

Reinforcement Learning 3
Introduction to Collections Framework

Reinforcement Learning 4
Introduction to Collections Framework
A
 
collection 
is an
object that represents a group of
objects.
A collections framework is a unified architecture for
representing and manipulating collections,
enabling collections to be manipulated independently of
implementation details.

Reinforcement Learning 5
Introduction to Collections Framework
The primary advantages of a collections framework are that
it:
Reduces programming effort 
by providing data structures and
algorithms so you don't have to write them yourself.
Increases performance 
by providing high-performance implementations
of data structures and algorithms. Because the various implementations of
each interface are interchangeable, programs can be 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 requiring you to learn
multiple adhoc collection APIs.
Reduces the effort required to design and implement APIs 
by not
requiring you to produce ad hoc collections APIs.
Fosters software reuse 
by providing a standard interface for collections
and algorithms with which to manipulate them.

Reinforcement Learning 6
Value Prediction with function Approximation
Difficulties:
In many tasks to which we would like to apply reinforcement
learning, most states encountered will never have been
experienced exactly before.
This will almost always be the case when the state or
action spaces include continuous variables or
complex sensations, such as a visual image.
Solution – generalize from previously experienced states
to the ones that have never been seen.

Collections Interface

Why collections?
Collections are used to hold a collection of objects.
List holds objects based on
order of insertion and
can hold non unique collection
Set holds objects
without any order and
are unique
Maps holds objects based on
a key and value pair,
unique key and
no specific order

20CS305 ADVANCED JAVA PROGRAMMING UNIT 1 9

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 sub classes of
Collection interface.
Hierarchy of Collection Framework:
The java.util package contains all the classes and interfaces
for the Collection framework.
20CS305 ADVANCED JAVA PROGRAMMING UNIT 1 10

20CS305 ADVANCED JAVA PROGRAMMING UNIT 1 11

Methods in Collections Interface

13

Iterable and Iterator Interface

15
Iterable Interface in Java

16
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:
Iterator Interface

List Interface

18

19

ArrayList

21

22

23

24

25
Method Description
boolean addAll(int
index,
Collection<?
extends E> c)
It
is used to append all the elements in the specified
collection,
starting at the specified position of the list.
void clear() It
is used to remove all of the elements from this list.
E
get(int index)
It
is used to fetch the element from the particular position of
the
list.
boolean
isEmpty()
It
returns true if the list is empty, otherwise false.
int
lastIndexOf(Object o)
It
is used to return the index in this list of the last occurrence
of
the specified element, or -1 if the list does not contain this
element.
Object[]
toArray()
It
is used to return an array containing all of the elements in
this
list in the correct order.
Object
clone()
It
is used to return a shallow copy of an ArrayList.

26

27

28

29
Output:
Returning
element: Apple
Mango
Dates
Banana
Grapes

30
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

31
Output:
Apple
Banana
Grapes
Mango
//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);
}
}
Sorting numbers...
1
11
21
51

32
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
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); 
 
  }   }  } 

33

34
//Creating another arraylist  
          ArrayList<String> al2=new ArrayList<String>();    
          al2.add("Ravi");    
          al2.add("Hanumat");    
          //Adding new elements to arraylist  
          al.addAll(al2);  
          System.out.println("Updated list : "+al);   
          //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);   
       }  
    }   

35
Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj,
Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []

36
import java.util.*;  
class ArrayList4{  
 public static void main(String args[]){  
    ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
           list.add("Ravi");//Adding object in arraylist  
           list.add("Vijay");  
           list.add("Ravi");  
           list.add("Ajay");  
            
           System.out.println("Traversing list through List Iterator:");  
           //Here, element iterates in reverse order  
              ListIterator<String> list1=list.listIterator(list.size());  
              while(list1.hasPrevious())  
              {  
                  String str=list1.previous();  
                  System.out.println(str);  
              }  
Output:
Traversing list through List Iterator:
Ajay
Ravi
Vijay
Ravi

37
  System.out.println("Traversing list through for loop:");  
           for(int i=0;i<list.size();i++)  
           {  
            System.out.println(list.get(i));     
           }  
              
        System.out.println("Traversing list through forEach() method:");  
        //The forEach() method is a new feature, introduced in Java 8.  
            list.forEach(a->{ //Here, we are using lambda expression  
                System.out.println(a);  
              });  
Output:
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach()
method:
Ravi
Vijay
Ravi
Ajay

38
             
            System.out.println("Traversing list through forEachRemaining() method:"
);  
              Iterator<String> itr=list.iterator();  
              itr.forEachRemaining(a-> //Here, we are using lambda expression  
              {  
            System.out.println(a);  
              });  
 }  
}   Output:
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay

39
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

LinkedList

41

42

43

44

45

46

47
Output:
[Volvo, BMW, Ford, Mazda]

48
Output:
Ravi
Vijay
Ravi
Ajay
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());  
  }  
 }  
}  

49
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);  

50
  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);  

51
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]
  //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);  
             
 }  

52
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]
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);   

53
  //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);  
          //Removing first element from the list  
              ll.removeLast();  
              System.out.println("After invoking removeLast() method: "+ll);  

54
   //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);   
       }  
    }                   

55
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: []

56
   //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);   
       }  
    }                   
Page 33

57

58
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

Set Interface

60
The set is an interface available in the java.util package.
The set interface extends the Collection interface.
An unordered collection or list in which duplicates are not allowed
is referred to as a collection interface.
The set interface is used to create the mathematical set.
The set interface use collection interface's methods to avoid the
insertion of the same elements.
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>();

HashSet

62
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 hash code.
HashSet is the best approach for search operations.
The initial default capacity of HashSet is 16, and the load factor is 0.75.

63
import java.util.*;  
class HashSet1{  
 public static void main(String args[]){  
  //Creating HashSet and adding elements  
    HashSet<String> set=new HashSet();  
           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:
Five
One
Four
Two
Three
Note: The order of the objects
printed are not predictable.

64

65

66
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());  
  }  
 }  
}  
Output:
Ajay
Vijay
Ravi
Note: HashSet doesn't allow
duplicate elements.

67
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);   

68
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:
           //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: "+s
et);  
           //Removing all the elements available in the set  
           set.clear();  
           System.out.println("After invoking clear() method: "+set);  
 }  
}  

69
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;  
}  
}  

70
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 & Netw
orking",
"Forouzan","Mc Graw Hill",4);  
    Book b3=new Book(103,"Operating System","Galvin","W
iley",6);  
    //Adding Books to HashSet  
    set.add(b1);  
    set.add(b2);  
    set.add(b3);  

71
    //Traversing HashSet  
    for(Book b:set){  
    System.out.println(b.id+" "+b.name+" "+b.author+" "+b.p
ublisher+" "+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

LinkedHashSet

73
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.
Note: Keeping the insertion order in the LinkedHashset has some
additional costs, both in terms of extra memory and extra CPU cycles.
Therefore, if it is not required to maintain the insertion order, go for
the lighter-weight HashMap or the HashSet instead.

74

75
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

76
import java.util.*;  
class LinkedHashSet2{  
 public static void main(String args[]){  
  LinkedHashSet<String> al=new LinkedHashSet<Strin
g>();  
  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
Ajay

TreeSet

78
•Java TreeSet class contains unique elements only like HashSet.
•Java TreeSet class access and retrieval times are quiet fast.
•Java TreeSet class doesn't allow null element.
•Java TreeSet class is non synchronized.
•Java TreeSet class maintains ascending order.
•Java TreeSet class contains unique elements only like HashSet.
•Java TreeSet class access and retrieval times are quite fast.
•Java TreeSet class doesn't allow null elements.
•Java TreeSet class is non-synchronized.
•Java TreeSet class maintains ascending order.
•The TreeSet can only allow those generic types that are comparable. For
example The Comparable interface is being implemented by the
StringBuffer class.

79

80

81

82

83

84
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

85
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

86
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
Highest Value: 66

87
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]
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));  
 }  
}  

88
Output:
Intial Set: [A, B, C, D, E]
Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]
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"));  
 }  
}  

89
import java.util.*;    
class Book implements Comparable
<Book>{    
int id;    
String name,author,publisher;    
int quantity;    
public Book(int id, String name, Stri
ng author, String publisher, int quan
tity) {    
    this.id = id;    
    this.name = name;    
    this.author = author;    
    this.publisher = publisher;    
    this.quantity = quantity;    
}    
// implementing the abstract metho
d  
public int compareTo(Book b) {    
    if(id>b.id){    
        return 1;    
    }else if(id<b.id){    
        return -1;    
    }else{    
    return 0;    
    }    
}    
}   

90
Output:
101 Data Communications & Networking Forouzan Mc Graw Hill 4
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
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);    
    }    
}    
}    

91
// important import statement  
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;  }  
  
}  

92
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.");  
  
}  

93
When we compile the above program, we get the ClassCastException, as shown
below.
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)
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.

Comparable Interface

95
Java Comparable interface is used to order the objects of the user-
defined class.
This interface is found in java.lang package and contains only one
method named compareTo(Object).
It provides a single sorting sequence only, i.e., you can sort the
elements on the basis of single data member only.
For example, it may be rollno, name, age or anything else.
compareTo(Object obj) method

public int compareTo(Object obj)
It is used to compare the current object with the specified object.
It returns
positive integer, if the current object is greater than the specified
object.
negative integer, if the current object is less than the specified
object.
zero, if the current object is equal to the specified object.

96
//student.java
class Student implements Comparable<Student>{  
int rollno;  
String name;  
int age;  
Student(int rollno,String name,int age){  
this.rollno=rollno;  
this.name=name;  
this.age=age;  
}  
  
public int compareTo(Student st){  
if(age==st.age)  
return 0;  
else if(age>st.age)  
return 1;  
else  
return -1;  
}  
}  

97
//test.java
import java.util.*;  
public class TestSort1{  
public static void main(String args[]){  
ArrayList<Student> al=new ArrayList<Student>();  
al.add(new Student(101,"Vijay",23));  
al.add(new Student(106,"Ajay",27));  
al.add(new Student(105,"Jai",21));  
  
Collections.sort(al);  
for(Student st:al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
}  
}  
Output:
105 Jai 21
101 Vijay 23
106 Ajay 27

Map Interface

99
•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 atmost one value. There 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.

100

101

102

103

104

105

106
//Non-generic  
import java.util.*;  
public class MapExample1 {  
public static void main(String[] args) {  
    Map map=new HashMap();  
    //Adding elements to map  
    map.put(1,"Amit");  
    map.put(5,"Rahul");  
    map.put(2,"Jai");  
    map.put(6,"Amit");  
    //Traversing Map  
    Set set=map.entrySet();//Converting to Set so that we can traverse  
    Iterator itr=set.iterator();  
    while(itr.hasNext()){  
        //
Converting to Map.Entry so that we can get key and value separately  
        Map.Entry entry=(Map.Entry)itr.next();  
        System.out.println(entry.getKey()+" "+entry.getValue());  
    }  
}  
}  
Output:
1 Amit
2 Jai
5 Rahul
6 Amit

107
import java.util.*;  
class MapExample2{  
 public static void main(String args[]){  
  Map<Integer,String> map=new HashMap<Integer,String>();  
  map.put(100,"Amit");  
  map.put(101,"Vijay");  
  map.put(102,"Rahul");  
  //Elements can traverse in any order  
  for(Map.Entry m:map.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  
Output:
102 Rahul
100 Amit
101 Vijay

108
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

109
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:
102=Rahul
101=Vijay
100=Amit

110
import java.util.*;  
class MapExample5{  
 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.comparingByValue())  
      //Performs an action for each element of this stream  
      .forEach(System.out::println);  
 }  
}  
Output:
100=Amit
102=Rahul
101=Vijay

HashMap Class

112
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
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 hashtable to implement Map interface.
This allows the execution time of basic operations, such as get() and put()
to be constant.

113
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

114
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());    
      }  
        
     
Output:
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana

115
      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());    
          }  
 }  
}  

116
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

117
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);  
   }      
}  

118
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}

119
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");    
      hm.put(102,"Rahul");   
      System.out.println("Initial list of elements:");  
     for(Map.Entry m:hm.entrySet())  
     {  
        System.out.println(m.getKey()+" "+m.getValue());   
     }  
    

120
     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());   
     }  
 }  
}  

121
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

122
import java.util.*;    
class Book {    
int id;    
String name,author,publisher;    
int quantity;    
public Book(int id, String name, String author, String publisher, i
nt quantity) {    
    this.id = id;    
    this.name = name;    
    this.author = author;    
    this.publisher = publisher;    
    this.quantity = quantity;    
}    
}    

123
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);  

124
//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

LinkedHashMap Class

126
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.

127
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

128
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]

129
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);    
   }      
}  
Output:
Before invoking remove() method: {101=Amit, 102=Vijay,
103=Rahul}
After invoking remove() method: {101=Amit, 103=Rahul}

130
import java.util.*;    
class Book {    
int id;    
String name,author,publisher;    
int quantity;    
public Book(int id, String name, String author, String publisher, i
nt quantity) {    
    this.id = id;    
    this.name = name;    
    this.author = author;    
    this.publisher = publisher;    
    this.quantity = quantity;    
}    
}    

131
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);  

132
//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

HashTable Class

134
Java Hashtable class implements a hashtable, which maps keys to values. It
inherits Dictionary class and implements the Map interface.
A Hashtable is an array of a list. Each list is known as a bucket. The position
of the bucket is identified by calling the hashcode() method. A Hashtable
contains values based on the key.
Java Hashtable class contains unique elements.
Java Hashtable class doesn't allow null key or value.
Java Hashtable class is synchronized.
The initial default capacity of Hashtable class is 11 whereas loadFactor is
0.75.

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

TreeMap Class

137
Java TreeMap class is a red-black tree based implementation. It provides an
efficient means of storing key-value pairs in sorted order.
Java TreeMap contains values based on the key. It implements the
NavigableMap interface and extends AbstractMap class.
Java TreeMap contains only unique elements.
Java TreeMap cannot have a null key but can have multiple null values.
Java TreeMap is non synchronized.
Java TreeMap maintains ascending order.

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

Properties Class

140
The Properties class represents a persistent set of properties. The Properties
can be saved to a stream or loaded from a stream. It belongs
to java.util package. Properties define the following instance variable. This
variable holds a default property list associated with a Properties object. 
Properties is a subclass of Hashtable.
It is used to maintain a list of values in which the key is a string and the value
is also a string i.e; it can be used to store and retrieve string type data from
the properties file.
Properties class can specify other properties list as it’s the default. If a
particular key property is not present in the original Properties list, the
default properties will be searched.
Properties object does not require external synchronization and Multiple
threads can share a single Properties object. Also, it can be used to retrieve
the properties of the system.

141
1. Properties(): This creates a Properties object that has no default values.
Properties p = new Properties();
2. Properties(Properties propDefault): The second creates an object that uses
propDefault for its default value.
Properties p = new Properties(Properties propDefault);

142
import java.util.*;  
import java.io.*;  
public class Test {  
public static void main(String[] args)throws Exception{  
Properties p=System.getProperties();  
Set set=p.entrySet();  
Iterator itr=set.iterator();  
while(itr.hasNext()){  
Map.Entry entry=(Map.Entry)itr.next();  
System.out.println(entry.getKey()+" = “ +entry.getValue());  
}  } }  
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD

Queue Interface

144
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.

145
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.

146

PriorityQueue Class

148
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.
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.

149
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())
;  
}  
}  
}  

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

DeQueue Interface

152
The interface called Deque is present in java.util package.
It is the sub type 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".

153

154

155

156

ArrayDeque Class

158
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.
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.

159
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

160
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");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
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

Utility Class

162
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 classname. It makes our code
more flexible for use while remaining modular.

163
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 key word 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.

164
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);
}
}

THANK YOU
https://www.javatpoint.com/java-deque
Page 70
Tags