unit-4 java collections frame work
unit-4 java collections frame work
Java collection framework is a collection of interfaces and classes used to storing and
processing a group of individual objects as a single unit. The java collection framework holds
several classes that provide a large number of methods to store and process a group of objects.
These classes make the programmer task super easy and fast.
The List, Queue, and Set stores single value as its element, whereas Map stores a pair of a key
and value as its element.
For example, the ArrayList class implements the List interface which is a subinterface of
the Collection Interface.
Subinterfaces of Collection
The Collection interface includes subinterfaces that are implemented by various classes in Java.
1. List Interface
The List interface is an ordered collection that allows us to add and remove elements like
an array.
2. Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics.
It cannot have duplicate elements.
3. Queue Interface
The Queue interface is used when we want to store and access elements in First In, First
Out(FIFO) manner.
Methods of Collection
The Collection interface includes various methods that can be used to perform different
operations on objects. These methods are available in all its subinterfaces.
removeAll() - removes all the elements of the specified collection from the collection
The List allows to access the elements based on the index value that starts with zero.
Classes that Implement List
Since List is an interface, we cannot create objects from it.
In order to use the functionalities of the List interface, we can use these classes:
ArrayList
LinkedList
Vector
Stack
These classes are defined in the Collections framework and implement the List interface.
SYNTAX:
Here, we have created objects list1 and list2 of classes ArrayList and LinkedList. These objects
can use the functionalities of the List interface.
Methods of List
The List interface includes all the methods of the Collection interface. Its because Collection is a
super interface of List.
Some of the commonly used methods of the Collection interface that's also available in the List
interface are:
Methods Description
iterator() returns iterator object that can be used to sequentially access elements of lists
clear() removes all the elements from the list (more efficient than removeAll())
size() returns the length of lists
Example
import java.util.ArrayList;
import java.util.List;
list_1.add(0, 10);
list_1.add(1, 20);
list_2.add(0, "BTech");
list_2.add(1, "Smart");
list_2.add(2, "Class");
list_1.addAll(1, list_2);
list_1.set(2, 10);
}}
Java Queue Interface
The Queue interface is a child interface of the Collection interface. The Queue interface is
available inside the java.util package. It defines the methods that are commonly used by classes
like PriorityQueue and ArrayDeque.
The Queue is used to organize a sequence of elements prior to the actual operation.
In order to use the functionalities of Queue, we need to use classes that implement it:
ArrayDeque
LinkedList
PriorityQueue
ArrayDeque, LinkedList and PriorityQueue implements the Queue interface in Java.
Some of the commonly used methods of the Queue interface are:
The Queue interface includes all the methods of the Collection interface. It is because
Collection is the super interface of Queue.
add() - Inserts the specified element into the queue. If the task is successful, add() returns true,
if not it throws an exception.
offer() - Inserts the specified element into the queue. If the task is successful, offer() returns
true, if not it returns false.
element() - Returns the head of the queue. Throws an exception if the queue is empty.
peek() - Returns the head of the queue. Returns null if the queue is empty.
remove() - Returns and removes the head of the queue. Throws an exception if the queue is
empty.
poll() - Returns and removes the head of the queue. Returns null if the queue is empty.
Example
import java.util.*;
queue.offer(10);
queue.offer(20);
queue.offer(30);
queue.offer(40);
queue.remove();
queue.poll();
Methods of Deque
Since Deque extends the Queue interface, it inherits all the methods of the Queue interface.
Besides methods available in the Queue interface, the Deque interface also includes the
following methods:
addFirst() - Adds the specified element at the beginning of the deque. Throws an exception if
the deque is full.
addLast() - Adds the specified element at the end of the deque. Throws an exception if the
deque is full.
offerFirst() - Adds the specified element at the beginning of the deque. Returns false if the
deque is full.
offerLast() - Adds the specified element at the end of the deque. Returns false if the deque is
full.
getFirst() - Returns the first element of the deque. Throws an exception if the deque is empty.
getLast() - Returns the last element of the deque. Throws an exception if the deque is empty.
peekFirst() - Returns the first element of the deque. Returns null if the deque is empty.
peekLast() - Returns the last element of the deque. Returns null if the deque is empty.
removeFirst() - Returns and removes the first element of the deque. Throws an exception if the
deque is empty.
removeLast() - Returns and removes the last element of the deque. Throws an exception if the
deque is empty.
pollFirst() - Returns and removes the first element of the deque. Returns null if the deque is
empty.
pollLast() - Returns and removes the last element of the deque. Returns null if the deque is
empty.
Example
import java.util.*;
deque.addFirst(10);
deque.addLast(20);
deque.offerFirst(5);
deque.offerLast(25);
deque.push(2);
In order to use functionalities of the Set interface, we can use these classes:
HashSet
LinkedHashSet
EnumSet
TreeSet
SortedSet
NavigableSet
Here, we have created a Set called animals. We have used the HashSet class to implement the
Set interface.
Methods of Set
The Set interface includes all the methods of the Collection interface. It's because
Collection is a super interface of Set.
Some of the commonly used methods of the Collection interface that's also available in
the Set interface are:
addAll() - adds all the elements of the specified collection to the set
iterator() - returns an iterator that can be used to access elements of the set sequentially
removeAll() - removes all the elements from the set that is present in another specified set
retainAll() - retains all the elements in the set that are also present in another specified set
containsAll() - returns true if the set contains all the elements of the specified collection
hashCode() - returns a hash code value (address of the element in the set)
Set Operations
The Java Set interface allows us to perform basic mathematical set operations like union,
intersection, and subset.
Union - to get the union of two sets x and y, we can use x.addAll(y)
Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
Example:
import java.util.Set;
import java.util.HashSet;
class Main {
set1.add(3);
// Add elements
set2.add(1);
set2.add(2);
set2.addAll(set1);
We have created a sorted set called animals using the TreeSet class.
Methods of SortedSet
The SortedSet interface includes all the methods of the Set interface. It's because Set is a super
interfaceof SortedSet.
comparator() - returns a comparator that can be used to order elements in the set
headSet(element) - returns all the elements of the set before the specified element
tailSet(element) - returns all the elements of the set after the specified element including the
specified element
subSet(element1, element2) - returns all the elements between the element1 and element2
including element1
Example
import java.util.*;
sortedSet.add(10);
sortedSet.add(20);
sortedSet.add(5);
sortedSet.add(40);
sortedSet.add(30);
Here, we have created a navigable set named numbers of the TreeSet class.
Methods of NavigableSet
The NavigableSet is considered as a type of SortedSet. It is because NavigableSet extends the
SortedSet interface.Hence, all SortedSet methods are also available in NavigableSet.
However, some of the methods of SortedSet (headSet(), tailSet() and subSet()) are defined
differently in NavigableSet.
headSet(element, booleanValue)
The headSet() method returns all the elements of a navigable set before the specified element
(which is passed as an argument).
If true is passed as a booleanValue, the method returns all the elements before the specified
element including the specified element.
tailSet(element, booleanValue)
The tailSet() method returns all the elements of a navigable set after the specified element
(which is passed as an argument) including the specified element.
If false is passed as a booleanValue, the method returns all the elements after the specified
element without including the specified element.
The subSet() method returns all the elements between e1 and e2 including e1.
The bv1 and bv2 are optional parameters. The default value of bv1 is true, and the default value
of bv2 is false.
If false is passed as bv1, the method returns all the elements between e1 and e2 without
including e1.
If true is passed as bv2, the method returns all the elements between e1 and e2, including e1.
descendingIterator() - returns an iterator that can be used to iterate over a set in reverse order
ceiling() - returns the lowest element among those elements that are greater than or equal to
the specified element
floor() - returns the greatest element among those elements that are less than or equal to the
specified element
higher() - returns the lowest element among those elements that are greater than the specified
element
lower() - returns the greatest element among those elements that are less than the specified
element
pollFirst() - returns and removes the first element from the set
pollLast() - returns and removes the last element from the set
Example
import java.util.*;
navSet.add(10);
navSet.add(20);
navSet.add(5);
navSet.add(40);
navSet.add(30);
}
Collection classes in java:
ArrayList class:
In Java, we use the ArrayList class to implement the functionality of resizable-arrays.
Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we
can create arraylists in Java:
Add elements
Access elements
Change elements
Remove elements
For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("C");
languages.add("Python");
System.out.println("ArrayList: " + languages);
}
}
Output
ArrayList: [Java, C, Python]
In the above example, we have created an ArrayList named languages. Here, we have
used the add() method to add elements to languages.
For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
animals.add("Cat");
animals.add("Dog");
animals.add("Cow");
System.out.println("ArrayList: " + animals);
In the above example, we have used the get() method with parameter 1. Here, the
method returns the element at index 1.
We can also access elements of the ArrayList using the iterator() method.
For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Kotlin");
languages.add("C++");
System.out.println("ArrayList: " + languages);
languages.set(2, "JavaScript");
System.out.println("Modified ArrayList: " + languages);
}
}
Output
ArrayList: [Java, Kotlin, C++]
Modified ArrayList: [Java, Kotlin, JavaScript]
In the above example, we have created an ArrayList named languages. Notice the
line,language.set(2, "JavaScript");
Here, the set() method changes the element at index 2 to JavaScript.
4. Remove ArrayList Elements
To remove an element from the arraylist, we can use the remove() method of the ArrayList
class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.println("ArrayList: " + animals);
String str = animals.remove(2);
System.out.println("Updated ArrayList: " + animals);
System.out.println("Removed Element: " + str);
}
}
Output
ArrayList: [Dog, Cat, Horse]
Updated ArrayList: [Dog, Cat]
Removed Element: Horse
Here, the remove() method takes the index number as the parameter. And, removes the
element specified by the index number.
Besides the above basic methods, there are some more ArrayList methods that are
commonly used.
Methods Descriptions
size() Returns the length of the arraylist.
sort() Sort the arraylist elements.
clone() Creates a new arraylist with the same element, size, and capacity.
contains() Searches the arraylist for the specified element and returns a boolean
result.
ensureCapacity() Specifies the total element the arraylist can contain.
isEmpty() Checks if the arraylist is empty.
indexOf()Searches a specified element in an arraylist and returns the index of the
element
Prev - stores an address of the previous element in the list. It is null for the first element
Next - stores an address of the next element in the list. It is null for the last element
Add elements
Access elements
Change elements
Remove elements
We can use the add() method to add an element (node) at the end of the LinkedList. For example,
import java.util.LinkedList;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
animals.add(1, "Horse");
Output
In the above example, we have created a LinkedList named animals. Here, we have used the add()
method to add elements to animals.
The get() method of the LinkedList class is used to access an element from the LinkedList. For example,
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
Output
In the above example, we have used the get() method with parameter 1. Here, the method returns the
element at index 1.
The set() method of LinkedList class is used to change elements of the LinkedList. For example,
import java.util.LinkedList;
class Main {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java");
Output
In the above example, we have created a LinkedList named languages. Notice the line,
languages.set(3, "Kotlin");
The remove() method of the LinkedList class is used to remove an element from the LinkedList. For
example,
import java.util.LinkedList;
class Main {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Kotlin");
}
}
Output
Here, the remove() method takes the index number as the parameter. And, removes the element
specified by the index number.
Other Methods
Methods Description
In order to create a hash set, we must import the java.util.HashSet package first.
Methods of HashSet
The HashSet class provides various methods that allow us to perform various operations on the set.
addAll() - inserts all the elements of the specified collection to the set
For example,
import java.util.HashSet;
class Main {
evenNumber.add(2);
evenNumber.add(4);
evenNumber.add(6);
numbers.addAll(evenNumber);
numbers.add(5);
Output
HashSet: [2, 4, 6]
import java.util.HashSet;
import java.util.Iterator;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(6);
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
Output
HashSet: [2, 5, 6]
Remove Elements
remove() - removes the specified element from the set
For example,
import java.util.HashSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(6);
Output
HashSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? True
Set operations
The various methods of the HashSet class can also be used to perform various set operations.
Union of Sets
To perform the union between two sets, we can use the addAll() method. For example,
import java.util.HashSet;
class Main {
evenNumbers.add(2);
evenNumbers.add(4);
numbers.add(1);
numbers.add(3);
numbers.addAll(evenNumbers);
Output
HashSet1: [2, 4]
HashSet2: [1, 3]
Union is: [1, 2, 3, 4]
Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method. For example
import java.util.HashSet;
class Main {
primeNumbers.add(2);
primeNumbers.add(3);
evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.retainAll(primeNumbers);
Output
HashSet1: [2, 3]
HashSet2: [2, 4]
Difference of Sets
To calculate the difference between the two sets, we can use the removeAll() method. For example,
import java.util.HashSet;
class Main {
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
oddNumbers.add(1);
oddNumbers.add(3);
oddNumbers.add(5);
primeNumbers.removeAll(oddNumbers);
Output
HashSet1: [2, 3, 5]
HashSet2: [1, 3, 5]
Difference: [2]
Subset
To check if a set is a subset of another set or not, we can use the containsAll() method. For example,
import java.util.HashSet;
class Main {
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
primeNumbers.add(2);
primeNumbers.add(3);
Output
HashSet1: [1, 2, 3, 4]
HashSet2: [2, 3]
Java TreeSet
The TreeSet class of the Java collections framework provides the functionality of a tree data structure.
Creating a TreeSet
In order to create a tree set, we must import the java.util.TreeSet package first.
Once we import the package, here is how we can create a TreeSet in Java
Methods of TreeSet
The TreeSet class provides various methods that allow us to perform various operations on the set.
addAll() - inserts all the elements of the specified collection to the set
For example,
import java.util.TreeSet;
class Main {
evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.add(6);
numbers.add(1);
numbers.addAll(evenNumbers);
Output
TreeSet: [2, 4, 6]
import java.util.Iterator;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(6);
// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
Output
TreeSet: [2, 5, 6]
Remove Elements
remove() - removes the specified element from the set
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(6);
Output
TreeSet: [2, 5, 6]
Is 5 removed? true
For example,
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(6);
Output
TreeSet: [2, 5, 6]
First Number: 2
Last Number: 6
lower(element) - Returns the greatest element among those elements that are less than the specified
element.
ceiling(element) - Returns the lowest element among those elements that are greater than the specified
element. If the element passed exists in a tree set, it returns the element passed as an argument.
floor(element) - Returns the greatest element among those elements that are less than the specified
element. If the element passed exists in a tree set, it returns the element passed as an argument.
For example,
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
// Using higher()
// Using lower()
// Using ceiling()
// Using floor()
}
}
Output
TreeSet: [2, 4, 5, 6]
Using higher: 5
Using lower: 2
Using ceiling: 4
Using floor: 2
pollLast() - returns and removes the last element from the set
For example,
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
// Using pollFirst()
// Using pollLast()
Output
TreeSet: [2, 4, 5, 6]
The headSet() method returns all the elements of a tree set before the specified element (which is
passed as an argument).
If true is passed as a booleanValue, the method returns all the elements before the specified element
including the specified element.
For example,
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
Output
TreeSet: [2, 4, 5, 6]
tailSet(element, booleanValue)
The tailSet() method returns all the elements of a tree set after the specified element (which is passed as
a parameter) including the specified element.
If false is passed as a booleanValue, the method returns all the elements after the specified element
without including the specified element.
For example,
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
Output
TreeSet: [2, 4, 5, 6]
The bv1 and bv2 are optional parameters. The default value of bv1 is true, and the default value of bv2
is false.
If false is passed as bv1, the method returns all the elements between e1 and e2 without including e1.
If true is passed as bv2, the method returns all the elements between e1 and e2, including e1.
For example,
import java.util.TreeSet;
class Main {
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
Output
TreeSet: [2, 4, 5, 6]
Java PriorityQueue
The PriorityQueue class provides the functionality of the heap data structure.
Unlike normal queues, priority queue elements are retrieved in sorted order.
Suppose, we want to retrieve elements in the ascending order. In this case, the head of the priority
queue will be the smallest element. Once this element is retrieved, the next smallest element will be the
head of the queue.
Creating PriorityQueue
In order to create a priority queue, we must import the java.util.PriorityQueue package. Once we import
the package, here is how we can create a priority queue in Java.
Methods of PriorityQueue
The PriorityQueue class provides the implementation of all the methods present in the Queue interface.
offer() - Inserts the specified element to the queue. If the queue is full, it returns false.
For example,
import java.util.PriorityQueue;
class Main {
numbers.add(4);
numbers.add(2);
numbers.offer(1);
Output
PriorityQueue: [2, 4]
Here, we have created a priority queue named numbers. We have inserted 4 and 2 to the queue.
import java.util.PriorityQueue;
class Main {
numbers.add(4);
numbers.add(2);
numbers.add(1);
Output
PriorityQueue: [1, 4, 2]
Accessed Element: 1
For example,
import java.util.PriorityQueue;
class Main {
numbers.add(4);
numbers.add(2);
numbers.add(1);
Output
PriorityQueue: [1, 4, 2]
import java.util.PriorityQueue;
import java.util.Iterator;
class Main {
numbers.add(4);
numbers.add(2);
numbers.add(1);
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
Output
Methods Descriptions
contains(element) Searches the priority queue for the specified element.
Creating ArrayDeque
Here, Type indicates the type of the array deque. For example,
Methods of ArrayDeque
The ArrayDeque class provides implementations for all the methods present in Queue and Deque
interface.
add() - inserts the specified element at the end of the array deque
addFirst() - inserts the specified element at the beginning of the array deque
addLast() - inserts the specified at the end of the array deque (equivalent to add())
Note: If the array deque is full, all these methods add(), addFirst() and addLast() throws
IllegalStateException.
For example,
import java.util.ArrayDeque;
class Main {
// Using add()
animals.add("Dog");
// Using addFirst()
animals.addFirst("Cat");
// Using addLast()
animals.addLast("Horse");
Output
offerFirst() - inserts the specified element at the beginning of the array deque
offerLast() - inserts the specified element at the end of the array deque
Note: offer(), offerFirst() and offerLast() returns true if the element is successfully inserted; if the array
deque is full, these methods return false.
For example,
import java.util.ArrayDeque;
class Main {
// Using offer()
animals.offer("Dog");
// Using offerFirst()
animals.offerFirst("Cat");
// Using offerLast()
animals.offerLast("Horse");
Output
Note: If the array deque is empty, getFirst() and getLast() throws NoSuchElementException.
For example,
import java.util.ArrayDeque;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
Output
peekFirst() - returns the first element of the array deque (equivalent to peek())
For example,
import java.util.ArrayDeque;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Using peek()
// Using peekFirst()
// Using peekLast
Output
Note: If the array deque is empty, peek(), peekFirst() and getLast() throws NoSuchElementException.
remove() - returns and removes an element from the first element of the array deque
remove(element) - returns and removes the specified element from the head of the array deque
removeFirst() - returns and removes the first element from the array deque (equivalent to remove())
removeLast() - returns and removes the last element from the array deque
Note: If the array deque is empty, remove(), removeFirst() and removeLast() method throws an
exception. Also, remove(element) throws an exception if the element is not found.
For example,
import java.util.ArrayDeque;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
animals.add("Horse");
// Using remove()
// Using removeFirst()
// Using removeLast()
Output
poll() - returns and removes the first element of the array deque
pollFirst() - returns and removes the first element of the array deque (equivalent to poll())
pollLast() - returns and removes the last element of the array deque
Note: If the array deque is empty, poll(), pollFirst() and pollLast() returns null if the element is not found.
For example,
import java.util.ArrayDeque;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
animals.add("Horse");
// Using pollFirst()
// Using pollLast()
Output
To remove all the elements from the array deque, we use the clear() method. For example,
import java.util.ArrayDeque;
class Main {
animals.add("Cat");
animals.add("Horse");
// Using clear()
animals.clear();
Output
New ArrayDeque: []
descendingIterator() - returns an iterator that can be used to iterate over the array deque in reverse
order
In order to use these methods, we must import the java.util.Iterator package. For example,
import java.util.ArrayDeque;
import java.util.Iterator;
class Main {
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.print("ArrayDeque: ");
// Using iterator()
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
// Using descendingIterator()
while(desIterate.hasNext()) {
System.out.print(desIterate.next());
System.out.print(", ");
Output
Other Methods
Methods Descriptions
We use the following steps to access a collection of elements using the Iterator.
Step - 2: Use the method hasNext( ) to access to check does the collection has the next element. (Use a
loop).
Step - 3: Use the method next( ) to access each element from the collection. (use inside the loop).
Method Description
hasNext( ) Returns true if the collection has the next element, otherwise, it returns false.
Example
import java.io.*;
import java.util.*;
cityNames.add("Delhi");
cityNames.add("Mumbai");
cityNames.add("Kolkata");
cityNames.add("Chandigarh");
cityNames.add("Noida");
while (iterator.hasNext())
System.out.println();
Output:
CityNames elements:
for-each alternative
The Java for-each loop an alternative approach to traverse the array or collection in Java. It is mainly
used to traverse the array or collection elements. The advantage of the for-each loop is that it eliminates
the possibility of bugs and makes the code more readable. It is known as the for-each loop because it
traverses each element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order
Syntax :
Example
import java.util.*;
class ForEachExample2{
list.add("vimal");
list.add("sonoo");
list.add("ratan");
for(String s:list){
System.out.println(s); } } }
Output:
vimal
sonoo
rattan
Map interfaces and classes:
The java collection framework has an interface Map that is available inside the
java.util package. The Map interface is not a subtype of Collection interface.
Interface Description
Class Description
HashMap It implements the Map interface, but it doesn't maintain any
order.
In Java, we must import the java.util.Map package in order to use Map. Once we
import the package, we can create a map as
Here,
Methods of Map
The Map interface includes all the methods of the Collection interface. It is
because Collection is a super interface of Map.
Besides methods available in the Collection interface, the Map interface also
includes the following methods:
1. put(K, V) - Inserts the association of a key K and a value V into the map. If
the key is already present, the new value replaces the old value.
2. putAll() - Inserts all the entries from the specified map to this map.
3. putIfAbsent(K, V) - Inserts the association if the key K is not already
associated with the value V.
4. get(K) - Returns the value associated with the specified key K. If the key is
not found, it returns null.
5. getOrDefault(K, defaultValue) - Returns the value associated with the
specified key K. If the key is not found, it returns the defaultValue.
6. containsKey(K) - Checks if the specified key K is present in the map or not.
7. containsValue(V) - Checks if the specified value V is present in the map or
not.
8. replace(K, V) - Replace the value of the key K with the new specified value
V.
9. replace(K, oldValue, newValue) - Replaces the value of the key K with the
new value newValue only if the key K is associated with the value oldValue.
10.remove(K) - Removes the entry from the map represented by the key K.
11.remove(K, V) - Removes the entry from the map that has key K associated
with value V.
12.keySet() - Returns a set of all the keys present in a map.
13.values() - Returns a set of all the values present in a map.
14.entrySet() - Returns a set of all the key/value mapping present in a map.
The HashMap class of the Java collections framework provides the functionality of
the hash table data structure.
It stores elements in key/value pairs. Here, keys are unique identifiers used to
associate each value on a map.
Here, the type of keys is String and the type of values is Integer.
Add elements
Access elements
Change elements
Remove elements
To add a single element to the hashmap, we use the put() method of the
HashMap class. For example,
import java.util.HashMap;
class Main {
// create a hashmap
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
Output
Initial HashMap: {}
We can access the keys, values, and key/value pairs of the hashmap as set views
using keySet(), values(), and entrySet() methods respectively. For example,
import java.util.HashMap;
class Main {
languages.put(2, "Python");
languages.put(3, "JavaScript");
// using keySet()
// using values()
// using entrySet()
Output
Keys: [1, 2, 3]
We can use the replace() method to change the value associated with a key in a
hashmap. For example,
import java.util.HashMap;
class Main {
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
languages.replace(2, "C++");
Output
import java.util.HashMap;
class Main {
languages.put(1, "Java");
languages.put(2, "Python");
languages.put(3, "JavaScript");
Output
Method Description
LinkedHashMap Class
The LinkedHashMap class is a child class of HashMap, and it implements the Map
interface. The LinkedHashMap is used to store the data in the form of key, value
pair using hash table and linked list concepts.
Example
import java.util.*;
employeeInfo.put(1, "Raja");
employeeInfo.put(2, "Gouthami");
employeeInfo.put(3, "Heyansh");
employeeInfo.put(4, "Yamini");
employeeInfo.put(5, "ManuTej");
int id = read.nextInt();
if(employeeInfo.containsKey(id)) {
contactInfo.put(id, contactNo);
TreeMap Class
import java.util.*;
employeeInfo.put(1, "Raja");
employeeInfo.put(4, "Gouthami");
employeeInfo.put(5, "Heyansh");
employeeInfo.put(3, "Yamini");
employeeInfo.put(2, "ManuTej");
int id = read.nextInt();
if(employeeInfo.containsKey(id)) {
contactInfo.put(id, contactNo);
}
}}
WeakHashMap class
The WeakHashMap class of the Java collections framework provides the feature
of the hash table data structure.
Create a WeakHashMap
Example:
import java.util.WeakHashMap;
class Main {
Integer twoValue = 2;
Integer fourValue = 4;
// Inserting elements
numbers.put(two, twoValue);
numbers.put(four, fourValue);
two = null;
System.gc();
Output
As we can see, when the key two of a weak hashmap is set to null and perform
garbage collection, the key is removed.
Using the java Comparator, we can sort the elements based on data members of a
class. For example, we can sort based on rollNo, age, salary, marks, etc.
Method Description
int compare(Object obj1, Object obj2) It is used to compares the obj1 with o bj2 .
import java.util.*;
class Student{
String name;
float percentage;
}
class PercentageComparator implements Comparator<Student>{
public int compare(Student stud1, Student stud2) {
if(stud1.percentage < stud2.percentage)
return 1;
return -1;
}
}
Collections.sort(studList, com);
The java collection framework defines several algorithms as static methods that can be used
with collections and map objects.
All the collection algorithms in the java are defined in a class called Collections which defined in
the java.util package.
Method Description
max(Collection c) Returns the largest element from the collection c as
determined by natural ordering.
min(Collection c) Returns the smallest element from the collection c as
determined by natural ordering.
void reverse(List Reverses all the elements sequence in list.
list)
void shuffle(List Shuffles the elements in list.
list)
void sort(List list) Sorts the elements of the list as determined by their natural
ordering.
Example
import java.util.*;
Collections.sort(list);
System.out.println("List in ascending order => " + list);
Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}
The java collection framework has a class Arrays that provides methods for creating dynamic
array and perform various operations like search, asList, campare, etc.
The Arrays class in java is defined in the java.util package. All the methods defined by Arrays
class are static methods.
List<T> asList(T[] arr) It returns a fixed-size list backed by the specified
Arrays.
int binarySearch(T[] arr, It searches for the specified element in the array with
element) the help of Binary Search algorithm, and returns the
position.
boolean equals(T[] It returns true if the two specified arrays of booleans
arr1, T[] arr2) are equal to one another, otherwise retruns false.
int hashCode(T[] arr) It returns the hash code for the specified array.
void fill(T[] arr, T value) It assigns the specified value to each element of the
specified array.
void sort(T[] arr) It sorts the specified array into ascending order.
Example
import java.util.*;
Arrays.fill(arr1, 15);
System.out.print("fill Array1 with 15 => ");
for(int i:arr1)
System.out.print(i + ", ");
Arrays.sort(arr2);
System.out.print("\nArray2 in sorted order => ");
for(int i:arr2)
System.out.print(i + ", ");
}
}
Dictionary class
In java, the package java.util contains a class called Dictionary which works like a Map.
The Dictionary is an abstract class used to store and manage elements in the form of a
pair of key and value.
The Dictionary stores data as a pair of key and value. In the dictionary, each key
associates with a value. We can use the key to retrieve the value back when needed.
As Dictionary is an abstract class we can not create its object. It needs a child class like
Hashtable.
The Dictionary class in java has the following methods.
S.
No. Methods with Description
1 Dictionary( )
It's a constructor.
2 Object put(Object key, Object value)
Inserts a key and its value into the dictionary. Returns null on success;
returns the previous value associated with the key if the key is already
exist.
3 Object remove(Object key)
It returns the value associated with given key and removes the same;
Returns null if the key does not exist.
4 Object get(Object key)
It returns the value associated with given key; Returns null if the key does
not exist.
5 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
6 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise returns false.
8 int size( )
It returns the total number of elements in the dictionary.
Example
import java.util.*;
dict.put(1, "Rama");
dict.put(2, "Seetha");
dict.put(3, "Heyansh");
dict.put(4, "Varshith");
dict.put(5, "Manutej");
// elements()
System.out.print("\n\nValues in Dictionary\n=> ");
for (Enumeration i = dict.elements(); i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}
//get()
System.out.println("\n\nValue associated with key 3 => " + dict.get(3));
System.out.println("Value associated with key 30 => " + dict.get(30));
//size()
System.out.println("\nDictionary has " + dict.size() + " elements");
//isEmpty()
System.out.println("\nIs Dictionary empty? " + dict.isEmpty());
}
}
Hashtable class
In java, the package java.util contains a class called Hashtable which works like a HashMap but
it is synchronized. The Hashtable is a concrete class of Dictionary. It is used to store and manage
elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with
a value. Any non-null object can be used as a key or as a value. We can use the key to retrieve
the value back when needed.
Example
import java.util.*;
//put(key, value)
for(int i = 1; i <= 5; i++)
table.put(i, num.nextInt(100));
//get(key)
System.out.println("\nValue associated with key 3 => " + table.get(3));
System.out.println("Value associated with key 30 => " + table.get(30));
//keySet()
System.out.println("\nKeys => " + table.keySet());
//values()
System.out.println("\nValues => " + table.values());
//entrySet()
System.out.println("\nKey, Value pairs as a set => " + table.entrySet());
//hashCode()
System.out.println("\nHash code => " + table.hashCode());
//hashCode()
System.out.println("\nTotal number of elements => " + table.size());
//isEmpty()
System.out.println("\nEmpty status of Hashtable => " + table.isEmpty());
}
}
Properties class
In java, the package java.util contains a class called Properties which is a child class of Hashtable
class. Java has this built-in class Properties which allow us to save and load multiple values from
a file. This makes the class extremely useful for accessing data related to configuration.
🔔 In Properties class both key and value are String data type.
🔔 Using Properties class, we can load key, value pairs into a Properties object from a
stream.
Example
import java.io.*;
import java.util.*;
try {
configProperties.setProperty("userName", "btechsmartclass");
configProperties.setProperty("password", "java");
configProperties.setProperty("email", "[email protected]");
fos.close();
System.out.println("Configuration saved!!!");
catch(Exception e) {
}
Stack class
In java, the package java.util contains a class called Stack which is a child class of Vector class. It
implements the standard principle Last-In-First-Out of stack data structure.
The Stack has push method for inesrtion and pop method for deletion. It also has other utility methods.
In Stack, the elements are added to the top of the stack and removed from the top of the stack.
It pushes the element onto the stack and returns the same.
2 Object pop( )
S.No. Methods with Description
It returns the element on the top of the stack and removes the same.
4 Object peek( )
5 boolean empty()
Example
import java.util.*;
stack.push(num.nextInt(100));
}
Vector class
In java, the package java.util contains a class called Vector which implements the List interface.
The Vector is similar to an ArrayList. Like ArrayList Vector also maintains the insertion order. But Vector
is synchronized, due to this reason, it is rarly used in the non-thread application. It also lead to poor
performance.
boolean add(Object o)
Example
import java.util.*;
public class VectorClassExample {
public static void main(String[] args) {
Vector list = new Vector();
list.add(10);
list.add(30);
list.add(0, 100);
list.addElement(50);
System.out.println("Vector => " + list);
System.out.println("get(2) => " + list.get(2));
System.out.println("firstElement() => " + list.firstElement());
System.out.println("indexOf(50) => " + list.indexOf(50));
}
Other Utility classes in java
StringTokenizer class
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.
Methods of the StringTokenizer Class
Methods Description
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
Example program:
import java.util.StringTokenizer;
public class Simple{
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
Output:
my
name
is
akshara
BitSet class
The BitSet is a built-in class in java used to create a dynamic array of bits represented by
boolean values. The BitSet class is available inside the java.util package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a Vector
of bits.
The size of the array is flexible and can grow to accommodate additional bit as needed.
The default value of the BitSet is boolean false with a representation as 0 (off).
Example
import java.util.*;
bSet_1.set(10);
bSet_1.set(5);
bSet_1.set(0);
bSet_1.set(7);
bSet_1.set(20);
bSet_2.set(1);
bSet_2.set(15);
bSet_2.set(20);
bSet_2.set(77);
bSet_2.set(50);
bSet_1.and(bSet_2);
System.out.println("BitSet_1 after and with bSet_2 => " + bSet_1);
bSet_1.andNot(bSet_2);
System.out.println("BitSet_1 after andNot with bSet_2 => " + bSet_1);
bSet_2.set(2);
System.out.println("Bit at index 2 after set in bSet_2 => " + bSet_2.get(2));
}
}
Date class
The Date is a built-in class in java used to work with date and time in java. The Date class is
available inside the java.util package. The Date class represents the date and time with
millisecond precision.
Calendar class
The Calendar is a built-in abstract class in java used to convert date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. The Calendar class is
available inside the java.util package.
As the Calendar class is an abstract class, we can not create an object using it.
Example
import java.util.*;
public class CalendarClassExample {
public static void main(String[] args) {
}
}
Random class:
We can generate random numbers in Java using the Random class of Java.util package.
Using this Random class, we can generate a random number of the types integer, float,
double, long, and boolean. We have to follow below-mentioned steps to generate a
number using the Random class.
First, we have to import Java.util.Random class
Second, create an object of Random class
Invoke any of the following methods:
Methods with Description
Boolean nextBoolean()
It generates the next uniformly distributed pseudo-random boolean value.
double nextDouble()
It generates the next pseudo-random double number between 0.0 and 1.0.
float nextFloat()
It generates the next pseudo-random float number between 0.0 and 1.0..
int nextInt(int n)
It generates the next pseudo-random integer value between zero and n.
long nextLong()
It generates the next pseudo-random, uniformly distributed long value.
.
Example
import java.util.Random;
public class RandomClassExample {
public static void main(String[] args) {
Random rand = new Random();
Formatter class
The Formatter is a built-in class in java used for layout justification and alignment,
common formats for numeric, string, and date/time data, and locale-specific output in
java programming. The Formatter class is defined as final class inside
the java.util package.
S.No. Methods with Description
3 Locale locale()
It returns the locale set by the construction of the
invoking formatter.
Example
import java.util.*;
public class FormatterClassExample {
public static void main(String[] args) {
Formatter formatter=new Formatter();
Output :
-1325,78900
Hello Java
Decimal floating-point notation to 4 places:123.1235
value in 10 digits:0000000088
Scanner class:
The Scanner is a built-in class in java used for read the input from the user in java programming.
The Scanner class is defined inside the java.util package.
The Scanner class provides the easiest way to read input in a Java program.
The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is
whitespace.
The Scanner class provides various methods that allow us to read inputs of different types.
Method Description
Example program:
import java.util.Scanner;
public class ScannerClassExample {
System.out.println("\n------------------------------------------");
}}