0% found this document useful (0 votes)
5 views30 pages

Java Collections

The document provides an overview of Java's ArrayList and LinkedList classes, highlighting their characteristics, operations, and differences. ArrayList uses a dynamic array for storage, allowing for duplicate elements and maintaining insertion order, while LinkedList employs a doubly linked list structure for efficient manipulation. Additionally, the document discusses other collection classes like HashSet, LinkedHashSet, and TreeSet, detailing their unique features and performance characteristics.

Uploaded by

Nagothi Sailaja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views30 pages

Java Collections

The document provides an overview of Java's ArrayList and LinkedList classes, highlighting their characteristics, operations, and differences. ArrayList uses a dynamic array for storage, allowing for duplicate elements and maintaining insertion order, while LinkedList employs a doubly linked list structure for efficient manipulation. Additionally, the document discusses other collection classes like HashSet, LinkedHashSet, and TreeSet, detailing their unique features and performance characteristics.

Uploaded by

Nagothi Sailaja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 30

Java ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no
size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional
array. It is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can
use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
The important points about the Java ArrayList class are:
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.

o Java ArrayList class is non synchronized.

o Java ArrayList allows random access because the array works on an index basis.

o In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of
shifting needs to occur if any element is removed from the array list.(reason :
arraylist.add(index,30) before 1,2,3,4 then add(2,50) :1,2,50,3,4
o We can not create an array list of the primitive types, such as int, float, char, etc. It is required
to use the required wrapper class in such cases. For example:
1. ArrayList<int> al = ArrayList<int>(); // does not work
2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
o Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies
according to the elements getting added or removed from the list.
o OPERATIONS: add(element),

o add(index,element)

o addAll(Arrays.asList(specified elements))

o addAll(another ArrayList)

o remove(element)

o removeAll(Arrays.asList(particular elements))

o removeAll(another ArrayList)

o size()

o get(index)

o set(index,element)

o retainAll(elements) so that only that elements can hold that arraylist

o indexOf(element);

o sort()

Note : Iterator is used to traverse the elements in a collection like list,set, queue in ascending order
from first element to last element.
Iterator<> it = listname.iterator() for this we have to use hasNext() and next()
To traverse in a reverse order we have another techniques like
Collections.reverse(listname)
ListIterator to tranverse elements both in forward and backward directions
backward
ListIterator<String> it = list.listIterator(list.size()); for this we have to use hasPrevious() and
previous()
forward
ListIterator<String> it = list.listIterator(); for this we have to use hasNext() and next()
ListIterator<String> it = list.listIterator(position ); we can retrieve from specified postion

Java LinkedList Class


Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.
In Java, a LinkedList is a class that implements the List interface and represents a linked list data
structure. Unlike arrays, which store elements in contiguous memory locations, a linked list stores
elements as nodes, where each node contains the element itself and a reference (or pointer) to the next
node in the sequence.
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.

o Java LinkedList class maintains insertion order.

o Java LinkedList class is non synchronized.

o In Java LinkedList class, manipulation is fast because no shifting needs to occur.

o Java LinkedList class can be used as a list, stack or queue.

One of the key features of a LinkedList is its dynamic size, meaning it can grow or shrink as needed.
This is because each element is stored in its own node, allowing for efficient insertion and deletion
operations. However, accessing elements by index in a LinkedList is less efficient compared to
arrays, as it requires traversing the list from the beginning or end to reach the desired element.

The LinkedList class in Java provides various methods to manipulate the list, such as adding or
removing elements, accessing elements by index, and searching for elements. Additionally, it offers
methods to perform operations like adding elements at the beginning or end of the list, inserting
elements at specific positions, and removing elements by index or value.
Hierarchy of LinkedList Class
The List interface extends the Collection interface and represents an ordered collection of elements.
Lists allow duplicate elements and provide methods to access elements by their integer index.
The LinkedList class implements the List interface and represents a doubly linked list data structure.
A LinkedList consists of a series of nodes, where each node contains a reference to the next node and
the previous node in the sequence. It allows for efficient insertion and deletion operations, as each
node only needs to update its neighboring nodes' references. However, accessing elements by index in
a LinkedList is less efficient compared to an ArrayList, as it requires traversing the list from the
beginning or end to reach the desired element.
Doubly Linked List
In Java, a doubly linked list is a type of linked list in which each node contains a reference to the next
node and the previous node in the sequence. It allows for traversal of the list in both forward and
backward directions, making it different from a singly linked list that only allows traversal in one
direction.
One advantage of a doubly linked list is that it allows for more efficient removal of elements
compared to a singly linked list, as it is possible to directly access the previous node of a given node.
It makes it easier to remove elements from the middle of the list without having to traverse the entire
list.
In the case of a doubly linked list, we can add or remove elements from both sides.

However, one drawback of a doubly linked list is that it requires more memory compared to a singly
linked list, as each node contains an additional pointer to the previous node. Additionally, maintaining
the previous pointers adds complexity to the implementation of the list
1. LinkedList<String> ll=new LinkedList<String>();
Operations
add(element)
add(index,element)
addAll(index,Arrays.asList(elements))
addAll(another list)
addFirst(element)
addLast(element)
remove(index)-> strings,integers for all types
remove(element)
removeAll(Specified elements)
removeAll(Another list)

Java LinkedList Example: Book(User defined class)

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<book> list=new LinkedList<book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are
non-synchronized classes.
However, there are many differences between the ArrayList and LinkedList classes that are given
below.

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to store LinkedList internally uses a doubly linked list to
the elements. store the elements.

2) Manipulation with ArrayList is slow because it


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

3) An ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

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

There is no case of default capacity in a LinkedList.


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

LinkedList implements the doubly linked list of the


7) To be precise, an ArrayList is a resizable array.
list interface.

How to Sort Java ArrayList in Descending Order


Note : to print elements in an descending order we don’t have direct method so we use 2 step method
to sort method
Collections.sort(listname,Collections.reverse())

How to remove duplicates from ArrayList in Java?


To remove dupliates from ArrayList, we can convert it into Set. Since Set doesn't contain duplicate
elements, it will have only unique elements.

How to convert ArrayList to Array and Array to ArrayList in java


To convert an ArrayList to an array, you can use the toArray() method.
String[] array = arrayList.toArray(new String[0]);

To convert an array to an ArrayList, you can use Arrays.asList()


ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));

Difference between length of array and size() of ArrayList in Java


ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects
available in the collection.
Array has length property which provides the length or capacity of the Array. It is the total space
allocated during the intialization of the array
How to make ArrayList Read Only?
The read-only means unmodifiable view of Collection in which we can not perform any operation
which will change the collection through add(), remove() or set() method. We can obtain read-only
collection from the existing collection by calling Collections.unmodifiableCollection() method.

When to use ArrayList and LinkedList in Java


ArrayList provides constant time for search operation, so it is better to use ArrayList if searching is
more frequent operation than add and remove operation. The LinkedList provides constant time for
add and remove operations. So it is better to use LinkedList for manipulation.
ArrayList has O(1) time complexity to access elements via the get and set methods.
LinkedList has O(n/2) time complexity to access the elements.
LinkedLinked class implements Deque interface also, so you can get the functionality of double ended
queue in LinkedList. The ArrayList class doesn't implement Deque interface.
In sort, ArrayList is better to access data wherease LinkedList is better to manipulate data. Both
classes implements List interface.

How to reverse ArrayList in Java?


The reverse method of Collections class can be used to reverse any collection. It is a static method.
Collections.reverse(listname);

How to Compare Two ArrayList in Java


There are following ways to compare two ArrayList in Java:
o Java equals() method

boolean bool = firstList.equals(secondList); //returns false because lists are not equal

o Java removeAll() method

//removes all elements from the first list


//returns empty list if all the elements of first list match with elemencs of second list
secondList.removeAll(firstList);
//prints the element of second list which does not match with the element of the first li
st

o Java retainAll() method

//returns the common elements in both list


secondList.retainAll(firstList);

o Java ArrayList.contains() method


Java ArrayList.contains() method is used for comparing two elements of different ArrayList.
Java ArrayList.contains() method overrides the contains() method
of AbstrarctCollection<E> class.
o Java contentEquals() method

In this example, we have created two ArrayList firstList and secondList of String type.
We have created a static method compareList() which parses two
ArrayList ls1 and ls2 as an argument and returns a boolean value. The method converts a
list into String. The contentEquals() method compares the String to the specified
StringBuffer.

Java List

List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.

The List interface is found in the java.util package and inherits the Collection interface. It is a
factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and
backward directions. The implementation classes of List interface are ArrayList, LinkedList,
Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The
Vector class is deprecated since Java 5.

//Creating a List of type Integer using ArrayList

List<Integer> list=new ArrayList<Integer>();

//Creating a List of type String using LinkedList

List<String> list=new LinkedList<String>();

List can be implemented by arraylist and linkedlist

Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.

o HashSet contains unique elements only.

o HashSet allows null value.

o HashSet class is non synchronized.

o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.

o HashSet is the best approach for search operations.

o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Same operations performed by set also

Add,remove

Clear() to remove all elements


Java LinkedHashSet Class

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It
inherits the HashSet class and implements the Set interface.

The important points about the Java LinkedHashSet class are:

o Java LinkedHashSet class contains unique elements only like HashSet.

o Java LinkedHashSet class provides all optional set operations and permits null elements.

o Java LinkedHashSet class is non-synchronized.

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

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends the HashSet class, which implements the Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.
LinkedHashSet Class Declaration

TreeSet in Java is a collection class that implements the Set interface and stores unique elements
in a sorted order. It’s part of the Java java.util package and is commonly used when you need to
maintain a collection of sorted and unique items. Here’s a clear breakdown of TreeSet and how it
works:

Key Features of TreeSet

1. Sorted Order: Elements in a TreeSet are automatically sorted in natural order (e.g.,
alphabetical for strings, ascending for numbers) or in a custom order defined by a
Comparator.

2. Unique Elements: Like all Set implementations, TreeSet does not allow duplicate
elements.

3. Implements NavigableSet Interface: This provides additional methods to navigate


through the set (e.g., finding the closest matches, getting subsets).

4. Red-Black Tree: TreeSet is backed by a Red-Black tree, a balanced binary search tree,
which ensures efficient performance for insertions, deletions, and lookups.

Performance Characteristics

 Time Complexity: Operations like add, remove, and contains have a time complexity of
O(log n) because of the Red-Black tree.

 Traversal: It can efficiently iterate in ascending or descending order.

Common Operations in TreeSet

Here’s a guide to the most common TreeSet methods:

1. Adding Elements: Use add(element) to add an element. If the element already exists, it
won’t be added again.

2. Removing Elements: Use remove(element) to delete a specific element.

3. Checking for Elements: Use contains(element) to check if an element is present.

4. Getting Size: Use size() to get the number of elements in the TreeSet.

5. Iterating in Order: Use a for-each loop or an Iterator to iterate in sorted order.

Example of Using TreeSet

Here’s a simple example to demonstrate common TreeSet operations:


java

Copy code

import java.util.TreeSet;

public class TreeSetExample {

public static void main(String[] args) {

// Create a TreeSet of Integers

TreeSet<Integer> numbers = new TreeSet<>();

// Add elements to the TreeSet

numbers.add(10);

numbers.add(5);

numbers.add(15);

numbers.add(10); // Duplicate element, won't be added

// Display elements in sorted order

System.out.println("TreeSet elements: " + numbers); // Output: [5, 10, 15]

// Remove an element

numbers.remove(10);

// Check if an element exists

boolean containsFive = numbers.contains(5); // true

// Get the smallest (first) and largest (last) elements

System.out.println("First element: " + numbers.first()); // Output: 5


System.out.println("Last element: " + numbers.last()); // Output: 15

// Iterating in ascending order

System.out.println("Ascending Order:");

for (Integer num : numbers) {

System.out.print(num + " "); // Output: 5 15

// Iterating in descending order

System.out.println("\nDescending Order:");

for (Integer num : numbers.descendingSet()) {

System.out.print(num + " "); // Output: 15 5

Important Points to Remember

1. Duplicates Not Allowed: TreeSet ignores duplicate entries.

2. Natural Ordering: By default, TreeSet uses natural ordering (ascending).

3. Custom Sorting: You can pass a custom Comparator to TreeSet if you want a specific
order.

4. Null Values: TreeSet does not allow null elements, as it cannot determine the order for
null.

Use Cases of TreeSet

 Sorted Collection: When you need a sorted collection without duplicates, such as storing
unique names in alphabetical order.

 Range Views: Ideal for scenarios where you need subsets within a specific range, as
TreeSet allows retrieving elements in specific ranges using methods like subSet(),
headSet(), and tailSet().
In summary, TreeSet is an efficient collection for maintaining a sorted and unique set of
elements, useful for scenarios requiring ordering and fast lookups without duplicates.

In Java, a Queue is a collection that follows the First-In-First-Out (FIFO) principle. It is part of
the java.util package and provides functionality to handle elements in a sequence where elements
are added at the end (rear) and removed from the front (head). The Queue interface in Java has
multiple implementations, with LinkedList and PriorityQueue being the most commonly used
classes.

Key Features of Queue

1. FIFO Order: Items are added to the back (tail) of the queue and removed from the front
(head). This ensures that the first element added is the first one removed.

2. Methods for Adding and Removing:

o enqueue (add): Adding an element to the back.

o dequeue (remove): Removing an element from the front.

3. Types of Queues:

o LinkedList: Standard FIFO queue.

o PriorityQueue: Orders elements based on priority rather than insertion order.

Common Queue Operations

The Queue interface provides several methods to add, remove, and inspect elements. Here are
some commonly used methods:

1. Add Elements:

o add(E e): Adds an element to the queue. Throws an exception if the queue is full.

o offer(E e): Adds an element to the queue. Returns false if the queue is full (useful
in bounded queues).

2. Remove Elements:

o remove(): Removes and returns the head of the queue. Throws an exception if the
queue is empty.

o poll(): Removes and returns the head of the queue. Returns null if the queue is
empty.

3. Examine Elements:

o element(): Retrieves, but does not remove, the head of the queue. Throws an
exception if the queue is empty.
o peek(): Retrieves, but does not remove, the head of the queue. Returns null if the
queue is empty.

Example of Using a Queue (LinkedList)

Here’s a basic example of using Queue with LinkedList:

java

Copy code

import java.util.LinkedList;

import java.util.Queue;

public class QueueExample {

public static void main(String[] args) {

// Create a Queue using LinkedList

Queue<String> queue = new LinkedList<>();

// Add elements to the Queue

queue.add("A");

queue.add("B");

queue.add("C");

// Display the Queue

System.out.println("Queue: " + queue); // Output: Queue: [A, B, C]

// Access the first element without removing

System.out.println("Peek: " + queue.peek()); // Output: Peek: A

// Remove elements from the Queue


System.out.println("Removed: " + queue.poll()); // Output: Removed: A

System.out.println("Removed: " + queue.poll()); // Output: Removed: B

// Display the Queue after removals

System.out.println("Queue after removals: " + queue); // Output: Queue after removals: [C]

A PriorityQueue in Java is a special type of queue where elements are ordered based on their
priority rather than the insertion order. It is part of the java.util package and implements the
Queue interface. This makes it suitable for scenarios where the highest (or lowest) priority
element needs to be processed first.

Key Features of PriorityQueue

1. Order of Elements:

o By default, PriorityQueue uses natural ordering (e.g., ascending order for


numbers).

o You can define a custom ordering by providing a Comparator when you create
the queue.

2. No Fixed Order for Equal Priority: Elements with the same priority may not appear in
a fixed order.

3. Does Not Allow null Values: PriorityQueue doesn’t support null elements.

4. Heap Implementation: Internally, PriorityQueue is implemented using a min-heap,


which ensures that the smallest (or highest-priority) element is always at the head.

How PriorityQueue Works

In a PriorityQueue, elements with the highest priority are served first. For example, if integers are
added, the smallest integer will be dequeued first (by default). When custom priority is needed,
you can use a comparator to define specific rules for ordering.

Common Operations and Methods

Here are some frequently used methods:

1. Add Elements:
o add(E e): Adds an element to the queue. Throws an exception if it fails.

o offer(E e): Similar to add, but returns false if it fails instead of throwing an
exception.

2. Remove Elements:

o remove(): Removes and returns the highest-priority element. Throws an exception


if the queue is empty.

o poll(): Removes and returns the highest-priority element or null if the queue is
empty.

3. Examine Elements:

o peek(): Retrieves, but does not remove, the highest-priority element or returns
null if the queue is empty.

o element(): Similar to peek but throws an exception if the queue is empty.

Example of PriorityQueue

Here’s a simple example to demonstrate the functionality of PriorityQueue with default natural
ordering (smallest numbers first):

java

Copy code

import java.util.PriorityQueue;

public class PriorityQueueExample {

public static void main(String[] args) {

// Create a PriorityQueue of Integers

PriorityQueue<Integer> pq = new PriorityQueue<>();

// Add elements to the PriorityQueue

pq.add(20);

pq.add(10);

pq.add(30);
// Display elements (Note: Order may vary in the output, as they are in a heap)

System.out.println("PriorityQueue elements: " + pq); // Output may vary in order

// Access the highest priority element

System.out.println("Peek: " + pq.peek()); // Output: 10 (smallest element)

// Remove elements in priority order (smallest element first)

System.out.println("Removed: " + pq.poll()); // Output: 10

System.out.println("Removed: " + pq.poll()); // Output: 20

System.out.println("Removed: " + pq.poll()); // Output: 30

Example with Custom Comparator

To reverse the natural ordering, or to apply a specific rule, you can use a custom comparator.
Here’s an example using a comparator to create a max-priority queue (highest number first):

java

Copy code

import java.util.PriorityQueue;

import java.util.Comparator;

public class CustomPriorityQueueExample {

public static void main(String[] args) {

// Create a PriorityQueue with custom comparator (largest element has highest priority)

PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());


// Add elements to the PriorityQueue

pq.add(20);

pq.add(10);

pq.add(30);

// Elements in the PriorityQueue

System.out.println("PriorityQueue elements: " + pq); // Output may vary in order

// Remove elements in priority order (largest element first)

System.out.println("Removed: " + pq.poll()); // Output: 30

System.out.println("Removed: " + pq.poll()); // Output: 20

System.out.println("Removed: " + pq.poll()); // Output: 10

ava Deque Interface

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

Deque Interface declaration

1. public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface

Method Description

It is used to insert the specified element into


boolean add(object)
this deque and return true upon success.

It is used to insert the specified element into


boolean offer(object)
this deque.
It is used to retrieve and removes the head of
Object remove()
this deque.

It is used to retrieve and removes the head of


Object poll() this deque, or returns null if this deque is
empty.

It is used to retrieve, but does not remove, the


Object element()
head of this deque.

It is used to retrieve, but does not remove, the


Object peek() head of this deque, or returns null if this deque
is empty.

The method returns the head element of the


deque. The method does not remove any
Object peekFirst()
element from the deque. Null is returned by
this method, when the deque is empty.

The method returns the last element of the


deque. The method does not remove any
Object peekLast()
element from the deque. Null is returned by
this method, when the deque is empty.

Inserts the element e at the front of the queue.


Boolean offerFirst(e) If the insertion is successful, true is returned;
otherwise, false.

Inserts the element e at the tail of the queue. If


Object offerLast(e) the insertion is successful, true is returned;
otherwise, false.
ArrayDeque class

We know that it is not possible to create an object of an interface in Java. Therefore, for
instantiation, we need a class that implements the Deque interface, and that class is ArrayDeque.
It grows and shrinks as per usage. It also inherits the AbstractCollection class.

The important points about ArrayDeque class are:

o Unlike Queue, we can add or remove elements from both sides.

o Null elements are not allowed in the ArrayDeque.

o ArrayDeque is not thread safe, in the absence of external synchronization.

o ArrayDeque has no capacity restrictions.

o ArrayDeque is faster than LinkedList and Stack.

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:

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.

Advertisement

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Class Description

HashMap is the implementation of Map, but it


HashMap
doesn't maintain any order.

LinkedHashMap is the implementation of Map.


LinkedHashMap It inherits HashMap class. It maintains insertion
order.

TreeMap is the implementation of Map and


TreeMap
SortedMap. It maintains ascending order.

The Map interface in Java represents a collection of key-value pairs where each key is unique.
It’s commonly implemented by classes such as HashMap, LinkedHashMap, and TreeMap. Here
are some useful methods provided by the Map interface to work with key-value mappings:

1. Basic CRUD Operations

 put(K key, V value): Adds a key-value pair to the map or updates the value if the key
already exists.
 putIfAbsent(K key, V value): Adds the key-value pair only if the key is not already
present in the map.

 get(Object key): Retrieves the value associated with the specified key. Returns null if the
key does not exist.

 remove(Object key): Removes the key-value pair for the specified key and returns the
value, or null if the key does not exist.

 replace(K key, V newValue): Replaces the value associated with the specified key if it
exists.

 replace(K key, V oldValue, V newValue): Replaces the value if the key exists and is
currently mapped to the old value.

 clear(): Removes all entries from the map.

2. Bulk Operations

 putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the
specified map to this map.

3. Querying the Map

 containsKey(Object key): Checks if the map contains a mapping for the specified key.

 containsValue(Object value): Checks if the map contains one or more keys mapped to
the specified value.

 isEmpty(): Returns true if the map contains no key-value mappings.

 size(): Returns the number of key-value pairs in the map.

4. Iteration and Retrieval of Keys, Values, and Entries

 keySet(): Returns a Set view of all keys in the map.

 values(): Returns a Collection view of all values in the map.

 entrySet(): Returns a Set view of all key-value pairs (entries) in the map, allowing easy
iteration.

Map.Entry is a nested interface within the Map interface in Java. It represents a key-value pair
(an entry) in a Map. Using Map.Entry, you can work with individual entries in the map, making it
especially useful when iterating over entries.

Here’s a breakdown of how Map.Entry works and its main features.

Key Points about Map.Entry

1. Purpose: It represents a single key-value mapping (pair) in a Map.


2. Accessing Entries: You can retrieve a Set of entries in a map using the entrySet()
method, which returns a Set<Map.Entry<K, V>>. This allows you to iterate through each
entry in the map.

3. Methods in Map.Entry:

o getKey(): Returns the key of the entry.

o getValue(): Returns the value of the entry.

o setValue(V value): Replaces the value corresponding to this entry with the
specified value. This is useful if you want to update values directly while
iterating.

Example Usage

Here’s how to use Map.Entry with a HashMap to iterate over and manipulate the map’s entries:

java

Copy code

import java.util.HashMap;

import java.util.Map;

public class MapEntryExample {

public static void main(String[] args) {

// Create a HashMap with some key-value pairs

Map<String, Integer> map = new HashMap<>();

map.put("Alice", 30);

map.put("Bob", 25);

map.put("Charlie", 35);

// Using Map.Entry to iterate over the entries in the map

for (Map.Entry<String, Integer> entry : map.entrySet()) {

System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());


// Example: Updating value for a specific condition

if (entry.getKey().equals("Alice")) {

entry.setValue(31); // Update Alice's value directly in the map

// Print the updated map

System.out.println("Updated Map: " + map);

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

o Java HashMap contains values based on the key.

o Java HashMap contains only unique keys.

o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.

o Java HashMap maintains no order.

o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

What is Hashing

It is the process of converting an object into an integer value. The integer value helps in indexing
and faster searches.

What is HashMap

HashMap is a part of the Java collection framework. It uses a technique called Hashing. It
implements the map interface. It stores the data in the pair of Key and Value. HashMap contains
an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data
structure internally for storing Key and Value. There are four fields in HashMap.

Java LinkedHashMap class


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

o Java LinkedHashMap contains values based on the key.

o Java LinkedHashMap contains unique elements.

o Java LinkedHashMap may have one null key and multiple null values.

o Java LinkedHashMap is non synchronized.

o Java LinkedHashMap maintains insertion order.

o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Java TreeMap class

Java TreeMap class is a red-black tree based implementation. It provides an efficient means of
storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

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.

Map Methods

put(key,value)

get(key)

remove(key)

clear()

replace(key , new_val);

size()

Subclass of map -> Map.Entry is used to retrieve elements in the map

i.e getkey()

getValue()

setValue()

What is difference between HashMap and TreeMap?

HashMap TreeMap

1) HashMap can contain one null key. TreeMap cannot contain any null key.

2) HashMap maintains no order. TreeMap maintains ascending order.

Java Hashtable class

Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.

Points to remember

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

o Java Hashtable class contains unique elements.


o Java Hashtable class doesn't allow null key or value.

o Java Hashtable class is synchronized.

o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given below.

;HashMap Hashtable

1) HashMap is non synchronized. It is not-thread


Hashtable is synchronized. It is thread-safe and can
safe and can't be shared between many threads
be shared with many threads.
without proper synchronization code.

2) HashMap allows one null key and multiple null


Hashtable doesn't allow any null key or value.
values.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by


Hashtable is internally synchronized and can't be
calling this code
unsynchronized.
Map m = Collections.synchronizedMap(hashMap);

Hashtable is traversed by Enumerator and


6) HashMap is traversed by Iterator.
Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.

8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

You might also like