Java Unit 4
Java Unit 4
Collections
This is the frame work of java. You can call it as API also.
Java collections are the set of pre-defined classes and interfaces that helps programmer to
perform different kinds of data structure operations like sorting searching, traversing, storing
and processing data efficiently.
LIFO - Stack
FIFO - Queue
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of the
specified array.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
1 public boolean hasNext() It returns true if the iterator has more elements
otherwise it returns false.
2 public Object next() It returns the element and moves the cursor
pointer to the next element.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.
It contains only one abstract method. i.e.,
Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider
the following example.
import java.util.*;
class A
{
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");
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Notes:
The ArrayList allows duplicate elements, as shown with the two entries of "Ravi".
The use of an Iterator provides a way to traverse the elements of the ArrayList in the
order they were added.
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order and
is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.
import java.util.*;
public class A
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
while(itr.hasNext())
System.out.println(itr.next());
Output:
Ravi
Vijay
Ravi
Ajay
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including LinkedList and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating LinkedList:
o LinkedList<String> al=new LinkedList<String>(); creates a LinkedList to store
String objects.
5. Adding Elements:
o al.add("Ravi");, al.add("Vijay");, al.add("Ravi");, and al.add("Ajay"); add
elements to the LinkedList.
6. Creating Iterator:
o Iterator<String> itr=al.iterator(); creates an Iterator for the LinkedList.
7. Traversing the List:
o The while(itr.hasNext()) loop iterates through the LinkedList as long as there
are more elements.
o System.out.println(itr.next()); prints the next element in the iteration.
Notes:
The LinkedList allows duplicate elements, as shown with the two entries of "Ravi".
The use of an Iterator provides a way to traverse the elements of the LinkedList in the order
they were added.
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It
is synchronized and contains many methods that are not the part of Collection framework.
import java.util.*;
public class A
v.add("Amit");
v.add("Ashish");
v.add("Garima");
while(itr.hasNext())
System.out.println(itr.next());
Output:
Ayush
Amit
Ashish
Garima
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including Vector and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating Vector:
o Vector<String> v = new Vector<String>(); creates a Vector to store String
objects.
5. Adding Elements:
o v.add("Ayush");, v.add("Amit");, v.add("Ashish");, and v.add("Garima"); add
elements to the Vector.
6. Creating Iterator:
o Iterator<String> itr = v.iterator(); creates an Iterator for the Vector.
7. Traversing the Vector:
o The while(itr.hasNext()) loop iterates through the Vector as long as there are
more elements.
o System.out.println(itr.next()); prints the next element in the iteration.
Notes:
The Vector allows duplicate elements and maintains the order of insertion.
The use of an Iterator provides a way to traverse the elements of the Vector in the order they
were added.
Vector is synchronized and thread-safe, unlike ArrayList, but it is generally slower due to this
synchronization.
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
import java.util.*;
public class A {
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
while(itr.hasNext()) {
System.out.println(itr.next());
Output:
Ayush
Garvit
Amit
Ashish
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including Stack and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating Stack:
o Stack<String> stack = new Stack<String>(); creates a Stack to store String
objects.
5. Adding Elements:
o stack.push("Ayush");, stack.push("Garvit");, stack.push("Amit");,
stack.push("Ashish");, and stack.push("Garima"); add elements to the Stack.
6. Removing an Element:
o stack.pop(); removes the top element from the stack (LIFO - Last In First
Out). The element "Garima" will be removed.
7. Creating Iterator:
o Iterator<String> itr = stack.iterator(); creates an Iterator for the Stack.
8. Traversing the Stack:
o The while(itr.hasNext()) loop iterates through the Stack as long as there are
more elements.
o System.out.println(itr.next()); prints the next element in the iteration.
Notes:
The Stack allows duplicate elements and follows the LIFO (Last In First Out) principle.
The pop() method removes the top element from the stack, which in this case is "Garima".
The use of an Iterator provides a way to traverse the elements of the Stack. However, note
that iterating through a Stack in this way will show the elements in the order they were added,
not in the reverse order as might be expected when thinking of stack operations.
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that
is used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
There are various classes that implement the Queue interface, some of them are given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.
import java.util.*;
public class A {
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
while (itr.hasNext()) {
while (itr2.hasNext()) {
Output:
Amit Sharma
Raj
JaiShankar
Vijay Raj
Raj
Vijay Raj
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including PriorityQueue and Iterator.
2. Class Definition:
Notes:
The PriorityQueue orders elements according to their natural ordering (for strings, it's
lexicographical order) or by a comparator provided at queue construction time.
The element() and peek() methods are used to view the head of the queue. The difference is
that element() throws an exception if the queue is empty, while peek() returns null.
The remove() and poll() methods both remove the head of the queue, but poll() returns null if
the queue is empty, whereas remove() throws an exception.
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements
from both the side. Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
import java.util.*;
public class A {
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
// Traversing elements
System.out.println(str);
Output:
Gautam
Karan
Ajay
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including Deque and ArrayDeque.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String[] args) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating Deque:
o Deque<String> deque = new ArrayDeque<String>(); creates a Deque using
ArrayDeque to store String objects.
5. Adding Elements:
o deque.add("Gautam");, deque.add("Karan");, and deque.add("Ajay"); add
elements to the Deque.
6. Traversing Elements:
o The enhanced for loop for (String str : deque) iterates through each element in
the Deque.
o System.out.println(str); prints each element in the Deque.
Notes:
The ArrayDeque class provides a resizable array implementation of the Deque interface. It
has no capacity restrictions and can be used as both a queue and a stack.
Elements are added to the end of the deque using the add method.
The enhanced for loop is used to traverse and print each element in the deque in the order
they were added.
ArrayDeque is not thread-safe; if multiple threads access a Deque concurrently and at least
one of the threads modifies the deque, it must be synchronized externally.
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table
for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
import java.util.*;
public class A {
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
// Traversing elements
while (itr.hasNext()) {
System.out.println(itr.next());
Output:
Vijay
Ravi
Ajay
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including HashSet and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating HashSet:
o HashSet<String> set = new HashSet<String>(); creates a HashSet to store
String objects.
5. Adding Elements:
o set.add("Ravi");, set.add("Vijay");, set.add("Ravi");, and set.add("Ajay"); add
elements to the HashSet.
o Note: Adding "Ravi" twice demonstrates that HashSet does not allow
duplicate elements.
6. Traversing Elements:
o Iterator<String> itr = set.iterator(); creates an Iterator for the HashSet.
o The while(itr.hasNext()) loop iterates through the HashSet as long as there are
more elements.
o System.out.println(itr.next()); prints each element in the HashSet.
Notes:
The HashSet does not guarantee any specific iteration order of the elements.
Duplicate elements are not added to the HashSet; hence "Ravi" appears only once in the
output.
The use of an Iterator provides a way to traverse the elements of the HashSet.
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements.
It maintains the insertion order and permits null elements.
import java.util.*;
public class A {
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
// Traversing elements
while (itr.hasNext()) {
System.out.println(itr.next());
Output:
Ravi
Vijay
Ajay
Explanation:
1. Import Statement:
o import java.util.*; imports all the utility classes from the java.util package,
including LinkedHashSet and Iterator.
2. Class Definition:
Notes:
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.
import java.util.*;
public class A {
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
// Traversing elements
while (itr.hasNext()) {
System.out.println(itr.next());
Output:
Ajay
Ravi
Vijay
Explanation:
1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including TreeSet and Iterator.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating TreeSet:
o TreeSet<String> set = new TreeSet<String>(); creates a TreeSet to store
String objects.
5. Adding Elements:
o set.add("Ravi");, set.add("Vijay");, set.add("Ravi");, and set.add("Ajay"); add
elements to the TreeSet.
o Note: Adding "Ravi" twice demonstrates that TreeSet does not allow duplicate
elements.
6. Traversing Elements:
o Iterator<String> itr = set.iterator(); creates an Iterator for the TreeSet.
o The while(itr.hasNext()) loop iterates through the TreeSet as long as there are
more elements.
o System.out.println(itr.next()); prints each element in the TreeSet.
Notes:
The TreeSet automatically sorts the elements in their natural order (alphabetical order for
String objects).
Duplicate elements are not added to the TreeSet; hence "Ravi" appears only once in the
output.
The use of an Iterator provides a way to traverse the elements of the TreeSet.
A Map is useful if you have to search, update or delete elements on the basis of a key.
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.
Class Description
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in
the map only if it is not already specified.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and
values.
V compute(K key, BiFunction<? super It is used to compute a mapping for the specified key
K,? super V,? extends V> and its current mapped value (or null if there is no
remappingFunction) current mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given mapping
super K,? extends V> function, if the specified key is not already associated
mappingFunction) with a value (or is mapped to null), and enters it into
this map unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and
BiFunction<? super K,? super V,? its current mapped value if the value for the specified
extends V> remappingFunction) key is present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the
value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key
exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map
super V> action) until all entries have been processed or the action
throws an exception.
V get(Object key) This method returns the object that contains the value
associated with the key.
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty; returns
false if it contains at least one key.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a
super V,? super V,? extends V> value or is associated with null, associates it with the
remappingFunction) given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking
super V,? extends V> function) the given function on that entry until all entries have
been processed or the function throws an exception.
int size() This method returns the number of entries in the map.
import java.util.*;
class A {
map.put(100, "Amit");
map.put(101, "Vijay");
map.put(102, "Rahul");
Output:
100 Amit
101 Vijay
102 Rahul
Explanation:
1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including HashMap and Map.
2. Class Definition:
Notes:
The HashMap does not guarantee any specific order of the elements.
The for loop iterates over the entrySet of the HashMap, which contains all the key-value
pairs.
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and
value pair, where keys should be unique. If you try to insert the duplicate key, it will
replace the element of the corresponding key. It is easy to perform operations using
the key index like updation, deletion, etc. HashMap class is found in
the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows
us to store the null elements as well, but there should be only one null key. Since Java
5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits
the AbstractMap class and implements the Map interface.
Points to remember
HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements
extends V> m) of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the
given integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of
loadFactor) the hash map by using its arguments.
void clear() It is used to remove all of the mappings from this map.
Set keySet() It is used to return a set view of the keys contained in this
map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V It inserts the specified value with the specified key in the
value) map only if it is not already specified.
boolean remove(Object key, It removes the specified values with the associated specified
Object value) keys from the map.
V compute(K key, It is used to compute a mapping for the specified key and
BiFunction<? super K,? its current mapped value (or null if there is no current
super V,? extends V> mapping).
remappingFunction)
V computeIfAbsent(K key, It is used to compute its value using the given mapping
Function<? super K,? function, if the specified key is not already associated with
extends V> a value (or is mapped to null), and enters it into this map
mappingFunction) unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and its
BiFunction<? super K,? current mapped value if the value for the specified key is
super V,? extends V> present and non-null.
remappingFunction)
boolean This method returns true if some value equal to the value
containsValue(Object value) exists within the map, else return false.
boolean containsKey(Object This method returns true if some key equal to the key exists
key) within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? It performs the given action for each entry in the map until
super K,? super V> action) all entries have been processed or the action throws an
exception.
V get(Object key) This method returns the object that contains the value
associated with the key.
V getOrDefault(Object key, It returns the value to which the specified key is mapped, or
V defaultValue) defaultValue if the map contains no mapping for the key.
boolean isEmpty() This method returns true if the map is empty; returns false
if it contains at least one key.
V merge(K key, V value, If the specified key is not already associated with a value or
BiFunction<? super V,? is associated with null, associates it with the given non-null
super V,? extends V> value.
remappingFunction)
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V It replaces the old value with the new value for a specified
oldValue, V newValue) key.
void It replaces each entry's value with the result of invoking the
replaceAll(BiFunction<? given function on that entry until all entries have been
super K,? super V,? extends processed or the function throws an exception.
V> function)
int size() This method returns the number of entries in the map.
import java.util.*;
public class A {
map.put(1, "Mango");
map.put(2, "Apple");
map.put(3, "Banana");
map.put(4, "Grapes");
System.out.println("Iterating HashMap...");
// Traversing elements
Output:
Iterating HashMap...
1 Mango
2 Apple
3 Banana
4 Grapes
Explanation:
1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including HashMap and Map.
2. Class Definition:
o public class A defines the public class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating HashMap:
o HashMap<Integer, String> map = new HashMap<Integer, String>(); creates a
HashMap to store Integer keys and String values.
5. Adding Elements:
o map.put(1, "Mango");, map.put(2, "Apple");, map.put(3, "Banana");, and
map.put(4, "Grapes"); add key-value pairs to the HashMap.
6. Traversing Elements:
o for (Map.Entry m : map.entrySet()) iterates through the HashMap entries.
o System.out.println(m.getKey() + " " + m.getValue()); prints the key and value
of each entry.
Notes:
The HashMap does not guarantee any specific order of the elements.
The for loop iterates over the entrySet of the HashMap, which contains all the key-value
pairs.
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.
Points to remember
Constructor Description
LinkedHashMap(int capacity, It is used to initialize both the capacity and the load factor.
float loadFactor)
LinkedHashMap(int capacity, It is used to initialize both the capacity and the load factor
float loadFactor, boolean with specified ordering mode.
accessOrder)
Method Description
boolean containsValue(Object value) It returns true if the map maps one or more keys to
the specified value.
void forEach(BiConsumer<? super It performs the given action for each entry in the
K,? super V> action) map until all entries have been processed or the
action throws an exception.
void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.
import java.util.*;
class A {
hm.put(100, "Amit");
hm.put(101, "Vijay");
hm.put(102, "Rahul");
// Traversing elements
Output:
100 Amit
101 Vijay
102 Rahul
Explanation:
1. Import Statement:
o import java.util.*; imports all utility classes from the java.util package,
including LinkedHashMap and Map.
2. Class Definition:
o class A defines the class named A.
3. Main Method:
o public static void main(String args[]) is the entry point of the Java application.
It takes an array of String arguments.
4. Creating LinkedHashMap:
o LinkedHashMap<Integer,String> hm = new
LinkedHashMap<Integer,String>(); creates a LinkedHashMap to store Integer
keys and String values.
5. Adding Elements:
o hm.put(100, "Amit");, hm.put(101, "Vijay");, and hm.put(102, "Rahul"); add
key-value pairs to the LinkedHashMap.
6. Traversing Elements:
o for (Map.Entry m : hm.entrySet()) iterates through the LinkedHashMap
entries.
o System.out.println(m.getKey() + " " + m.getValue()); prints the key and value
of each entry.
Notes:
The for loop iterates over the entrySet of the LinkedHashMap, which contains all the key-
value pairs.
import java.util.*;
public class A {
map.put(101, "Amit");
map.put(102, "Vijay");
map.put(103, "Rahul");
map.remove(102);
Output:
import java.util.*;
This imports the Java utility package, which includes the Map and LinkedHashMap classes.
2. Class Definition:
public class A {
3. Main Method:
This is the entry point for the program. The main method is where the program starts
executing.
4. Creating a LinkedHashMap:
Creates a LinkedHashMap named map that maps Integer keys to String values.
map.put(101, "Amit");
map.put(102, "Vijay");
map.put(103, "Rahul");
Adds three entries to the map with keys 101, 102, and 103 and corresponding values "Amit",
"Vijay", and "Rahul".
map.remove(102);
Prints the map after the removal of the entry with key 102.
Java TreeMap class is a red-black tree based implementation. It provides an efficient means
of storing key-value pairs in sorted order.
o Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.
TreeMap() It is used to construct an empty tree map that will be sorted usin
natural order of its key.
TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will be sorted u
comparator) the comparator comp.
TreeMap(Map<? extends K,? extends It is used to initialize a treemap with the entries from m, which w
V> m) sorted using the natural order of the keys.
TreeMap(SortedMap<K,? extends V> It is used to initialize a treemap with the entries from the SortedMap
m) which will be sorted in the same order as sm.
Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least key,
greater than or equal to the specified key, or null if
there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key
or null if there is no such key.
Comparator<? super K> It returns the comparator that arranges the key in
comparator() order, or null if the map uses the natural ordering.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal to the
specified key, or null if there is no such key.
void forEach(BiConsumer<? super It performs the given action for each entry in the map
K,? super V> action) until all entries have been processed or the action
throws an exception.
SortedMap<K,V> headMap(K It returns the key-value pairs whose keys are strictly
toKey) less than toKey.
NavigableMap<K,V> headMap(K It returns the key-value pairs whose keys are less than
toKey, boolean inclusive) (or equal to if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the given
key, or null if there is no such key.
Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key,
or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the given
key, or null if there is no such key.
V put(K key, V value) It inserts the specified value with the specified key in
the map.
void putAll(Map<? extends K,? It is used to copy all the key-value pair from one map
extends V> map) to another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, It replaces the old value with the new value for a
V newValue) specified key.
void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.
SortedMap<K,V> tailMap(K It returns key-value pairs whose keys are greater than
fromKey) or equal to fromKey.
NavigableMap<K,V> tailMap(K It returns key-value pairs whose keys are greater than
fromKey, boolean inclusive) (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping for the
specified key.
boolean containsValue(Object It returns true if the map maps one or more keys to
value) the specified value.
V get(Object key) It is used to return the value to which the map maps
the specified key.
V remove(Object key) It removes the key-value pair of the specified key from
the map.
class A {
map.put(100, "Amit");
map.put(102, "Ravi");
map.put(101, "Vijay");
map.put(103, "Rahul");
Output:
100 Amit
101 Vijay
102 Ravi
103 Rahul
import java.util.*;
This imports the Java utility package, which includes the Map and TreeMap classes.
2. Class Definition:
class A {
3. Main Method:
This is the entry point for the program. The main method is where the program starts
executing.
4. Creating a TreeMap:
Creates a TreeMap named map that maps Integer keys to String values.
map.put(100, "Amit");
map.put(102, "Ravi");
map.put(101, "Vijay");
map.put(103, "Rahul");
Adds four entries to the map with keys 100, 102, 101, and 103 and corresponding values
"Amit", "Ravi", "Vijay", and "Rahul".
Iterates over the entries of the map using a for-each loop. Each entry is printed with its key
and value.
Points to remember
Constructor Description
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that
contains a specified initial capacity.
Hashtable(int capacity, It is used to create a hash table having the specified initial
float loadFactor) capacity and loadFactor.
Hashtable(Map<? extends It creates a new hash table with the same mappings as the
K,? extends V> t) given Map.
V compute(K key, BiFunction<? It is used to compute a mapping for the specified key
super K,? super V,? extends V> and its current mapped value (or null if there is no
remappingFunction) current mapping).
V computeIfAbsent(K key, It is used to compute its value using the given mapping
Function<? super K,? extends V> function, if the specified key is not already associated
mappingFunction) with a value (or is mapped to null), and enters it into this
map unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and
BiFunction<? super K,? super V,? its current mapped value if the value for the specified key
extends V> remappingFunction) is present and non-null.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? It performs the given action for each entry in the map
super K,? super V> action) until all entries have been processed or the action throws
an exception.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped,
defaultValue) or defaultValue if the map contains no mapping for the
key.
int hashCode() It returns the hash code value for the Map
Set<K> keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, If the specified key is not already associated with a value
BiFunction<? super V,? super V,? or is associated with null, associates it with the given
extends V> remappingFunction) non-null value.
V put(K key, V value) It inserts the specified value with the specified key in the
hash table.
void putAll(Map<? extends K,? It is used to copy all the key-value pair from map to
extends V> t)) hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value
(or is mapped to null) associates it with the given value
and returns null, else returns the current value.
boolean remove(Object key, It removes the specified values with the associated
Object value) specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V It replaces the old value with the new value for a
oldValue, V newValue) specified key.
void replaceAll(BiFunction<? It replaces each entry's value with the result of invoking
super K,? super V,? extends V> the given function on that entry until all entries have
function) been processed or the function throws an exception.
boolean contains(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsValue(Object This method returns true if some value equal to the value
value) exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key
exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty;
returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and
rehashes all of its keys.
V get(Object key) This method returns the object that contains the value
associated with the key.
V remove(Object key) It is used to remove the key and its value. This method
returns the value associated with the key.
int size() This method returns the number of entries in the hash
table.
import java.util.*;
class A {
hm.put(100, "Amit");
hm.put(102, "Ravi");
hm.put(101, "Vijay");
hm.put(103, "Rahul");
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
import java.util.*;
This imports the Java utility package, which includes the Map and Hashtable classes.
2. Class Definition:
class A {
3. Main Method:
This is the entry point for the program. The main method is where the program starts
executing.
4. Creating a Hashtable:
hm.put(100, "Amit");
hm.put(102, "Ravi");
hm.put(101, "Vijay");
hm.put(103, "Rahul");
Adds four entries to the hashtable with keys 100, 102, 101, and 103 and corresponding values
"Amit", "Ravi", "Vijay", and "Rahul".
Sorting in Collection
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are o
Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides metho
for sorting the elements of List type elements.
public void sort(List list): is used to sort the elements of List. List elements must be of the
Comparable type.
class A {
al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");
Collections.sort(al);
while (itr.hasNext()) {
System.out.println(itr.next());
Output:
Mukesh
Saurav
Tahir
Viru
Explanation:
1. Imports:
import java.util.*;
This line imports the java.util package, which includes the ArrayList, Collections, and
Iterator classes used in the program.
2. Class Definition:
class A {
3. Main Method:
This is the main method, which is the entry point of the program.
4. Creating an ArrayList:
5. Adding Elements:
al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");
Collections.sort(al);
7. Creating an Iterator:
while (itr.hasNext()) {
System.out.println(itr.next());
This loop iterates over the ArrayList and prints each element. The hasNext() method checks
if there are more elements, and the next() method returns the next element in the list.
on the basis of single data member only. For example, it may be rollno, name, age or
anything else.
o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
import java.util.*;
String name;
int rollNumber;
this.name = name;
this.rollNumber = rollNumber;
Collections.sort(students);
System.out.println(student);
Output:
Student{name='Saurav', rollNumber=12}
Student{name='Tahir', rollNumber=23}
Student{name='Viru', rollNumber=34}
Student{name='Mukesh', rollNumber=56}
Explanation:
1. Student Class:
String name;
int rollNumber;
this.name = name;
this.rollNumber = rollNumber;
The Student class has two fields, name and rollNumber, and a constructor to initialize these
fields.
3. compareTo Method:
The compareTo method defines the natural ordering of Student objects by rollNumber. If
this.rollNumber is less than other.rollNumber, the method returns a negative value; if they are
equal, it returns zero; and if this.rollNumber is greater, it returns a positive value.
4. toString Method:
The toString method provides a string representation of a Student object, which is useful for
printing.
The Main class contains the main method, which is the entry point of the program.
6. Adding Students:
Collections.sort(students);
This sorts the list of Student objects based on the rollNumber field, using the natural ordering
defined by the compareTo method.
System.out.println(student);
This iterates through the sorted list and prints each Student object.
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Method Description
public int compare(Object obj1, It compares the first object with the second object.
Object obj2)
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
Collections class
Collections class provides static methods for sorting the elements of a collection. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot
sort the elements of List. Collections class provides methods for sorting the elements of List
type elements also.
The Comparator interface in Java is used to define multiple ways of sorting objects that are
different from the natural ordering. It is especially useful when you want to sort objects in
more than one way. Below is an example demonstrating how to use the Comparator interface
to sort a list of custom objects by different fields.
Example:
Suppose we have a class Student with fields name and rollNumber, and we want to sort a list
of Student objects by both name and rollNumber.
Student Class:
import java.util.*;
class Student {
String name;
int rollNumber;
java
Copy code
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
// Sorting by name
System.out.println("Sorting by name:");
Collections.sort(students, new NameComparator());
for (Student student : students) {
System.out.println(student);
}
String name;
int rollNumber;
// Sorting by name
System.out.println("Sorting by name:");
Collections.sort(students, new NameComparator());
for (Student student : students) {
System.out.println(student);
}
Output:
Sorting by name:
Student{name='Mukesh', rollNumber=56}
Student{name='Saurav', rollNumber=12}
Student{name='Tahir', rollNumber=23}
Student{name='Viru', rollNumber=34}
When to Use:
Use Comparable when there is a natural and consistent way to order objects of a class
and you expect this to be the primary way objects will be compared.
Use Comparator when you need to define multiple ways to compare objects, or if you
cannot modify the class whose objects need to be compared.
It can be used to get property value based on the property key. The Properties class
provides methods to get data from the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.
Method Description
public String It searches for the property with the specified key.
getProperty(String key,
String defaultValue)
public void list(PrintStream It is used to print the property list out to the specified
out) output stream.
public void list(PrintWriter It is used to print the property list out to the specified
out)) output stream.
public Set<String> It returns a set of keys in from property list where the
stringPropertyNames() key and its corresponding value are strings.
Properties p = System.getProperties();
while (itr.hasNext()) {
Output:
awt.toolkit = sun.awt.X11.XToolkit
java.specification.version = 11
sun.cpu.isalist =
sun.jnu.encoding = ANSI_X3.4-1968
java.class.path = /tmp/qjXCZTi3ew
java.vm.vendor = SAP SE
sun.arch.data.model = 64
java.vendor.url = https://sapmachine.io/
user.timezone =
os.name = Linux
java.vm.specification.version = 11
sun.java.launcher = SUN_STANDARD
user.country = US
sun.boot.library.path = /usr/lib/jvm/sapmachine-11/lib
sun.java.command = Test
jdk.debug = release
sun.cpu.endian = little
user.home = /home/compiler
user.language = en
java.version.date = 2024-01-16
java.home = /usr/lib/jvm/sapmachine-11
file.separator = /
java.vm.compressedOopsMode = 32-bit
line.separator =
java.awt.graphicsenv = sun.awt.X11GraphicsEnvironment
java.runtime.version = 11.0.22+7-LTS-sapmachine
user.name = compiler
path.separator = :
os.version = 6.1.75+
file.encoding = ANSI_X3.4-1968
java.vendor.version = SapMachine
java.vendor.url.bug = https://github.com/SAP/SapMachine/issues/new
java.io.tmpdir = /tmp
java.version = 11.0.22
user.dir = /home/compiler
os.arch = amd64
java.awt.printerjob = sun.print.PSPrinterJob
sun.os.patch.level = unknown
java.library.path = /usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib
java.vendor = SAP SE
java.vm.version = 11.0.22+7-LTS-sapmachine
java.specification.maintenance.version = 2
sun.io.unicode.encoding = UnicodeLittle
java.class.version = 55.0
1. Imports:
import java.util.*;
import java.io.*;
These lines import the necessary classes from the java.util and java.io packages. In this
specific code snippet, the java.io.* import is not required as file handling is not used.
2. Class Definition:
3. Main Method:
The main method is the entry point of the program and it throws a generic Exception to
handle any errors that may occur.
Properties p = System.getProperties();
This retrieves all system properties and stores them in a Properties object.
while (itr.hasNext()) {