0% found this document useful (0 votes)
25 views32 pages

Java Day 9

The document provides an overview of the Collection Framework in Java, explaining how it allows for the grouping of objects and addresses limitations of arrays such as fixed size and lack of built-in methods. It details the components of the framework, including interfaces, implementations, and algorithms, and highlights the benefits of using collections for high performance and flexibility. Additionally, it covers specific collection types like List, ArrayList, and LinkedList, along with their methods and characteristics.

Uploaded by

Stu udy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views32 pages

Java Day 9

The document provides an overview of the Collection Framework in Java, explaining how it allows for the grouping of objects and addresses limitations of arrays such as fixed size and lack of built-in methods. It details the components of the framework, including interfaces, implementations, and algorithms, and highlights the benefits of using collections for high performance and flexibility. Additionally, it covers specific collection types like List, ArrayList, and LinkedList, along with their methods and characteristics.

Uploaded by

Stu udy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

📚 Collection Framework in Java

🧩 Grouping Objects with Arrays


If we want to group together the objects of a class, then we use array of objects.
Example:

String[] names = new String[3];


names[0] = "Chitranshi";
names[1] = "Anu";
names[2] = "Bhakti";

Create array of references

Assign object to each reference one by one

❌ Limitations with Arrays


1. Fixed Size Nature
Arrays have a fixed size. You can only add elements up to the specified size.
If you try to add more elements beyond the size, the JVM will raise an
exception:

ArrayIndexOutOfBoundsException .

2. Lack of Predefined Methods


Arrays do not have built-in methods for searching or sorting.
Developers have to write their own logic to perform these operations.

3. No Built-in Support for Set Behavior or Sorted Elements

If you want to keep only distinct elements

If you want to keep the elements always sorted, despite insertions and
deletions

📚 Collection Framework in Java 1


➤ Then the developer needs to write a lot of code, and writing highly efficient,
error-free code requires a lot of skill and experience.

✅ Solution: Collection Framework in Java


📌 What is a Collection?
A Collection is simply an object that groups multiple elements into a single
unit.

Collections are used to store, retrieve, manipulate, and communicate


aggregate data.

🧰 What Does the Collection Framework Contain?


1. Interfaces
Java provides a set of interfaces that form a hierarchy.
Interfaces allow manipulating collections independently of their
representations.

2. Implementations
It contains a set of classes that provide implementations of the interfaces.
In simple words:

These classes provide reusable data structures.

3. Algorithms
The Collection Framework provides a wide range of methods that perform
commonly used operations.

These methods offer reusable functionality.

🎯 What Does the Collection Framework Provide?


The Collection Framework provides a unified approach for representing and
manipulating collections.
It is designed to meet the following goals:

📚 Collection Framework in Java 2


1. High Performance Implementations

Dynamic Arrays

Linked Lists

Hash Tables

➤ Developers don't need to write their own implementation for these


structures.

2. High Degree of Interoperability

Works in a similar manner across different types of collections.

3. Flexibility

Easy to extend and adapt the in-built interfaces.

💡 Tip: All classes and interfaces related to the Collection


Framework are present in the java.util package.

📁 Collection Framework Contains Two Sections:


1. Normal Collection

→ Multiple objects are handled individually

2. Map
→ Multiple objects are handled in the form of key-value pairs

📚 Collection Framework in Java 3


java.util.Collection<E> Interface

🔧 Abstract Methods of Collection Interface


Method Description

Ensures that this collection contains the specified element (optional


operation). Returns true if the collection changed as a result of the
boolean add(E e)
call. Returns false if duplicates are not allowed and the element
already exists.

Adds all elements from the specified collection to this collection


boolean
(optional operation). Behavior is undefined if the specified collection
addAll(Collection<?
extends E> c) is modified while the operation is in progress or if it’s the same
collection.

Removes all elements from the collection (optional operation). After


void clear()
this call, the collection will be empty.

📚 Collection Framework in Java 4


Method Description

Returns true if the collection contains the specified element. More


boolean
formally, returns true if there exists an element e such that (o ==
contains(Object o)
null ? e == null : o.equals(e)) .

boolean
Returns true if this collection contains all the elements in the
containsAll(Collection<?
> c)
specified collection.

boolean equals(Object
Compares the specified object with this collection for equality.
o)

boolean isEmpty() Returns true if the collection contains no elements.

Returns an iterator over the elements in this collection. Order is not


Iterator<E> iterator()
guaranteed unless specified by the implementation class.

Removes a single instance of the specified element from the


boolean remove(Object
collection, if present (optional operation). Returns true if the
o)
element was present and removed.

boolean Removes all elements from this collection that are also contained in
removeAll(Collection<?> the specified collection (optional operation). After this call, no
c) elements from the specified collection will remain in this collection.

boolean Retains only the elements in this collection that are also contained
retainAll(Collection<?> in the specified collection (optional operation). Removes everything
c) else.

Returns the number of elements in this collection. If the size


int size()
exceeds Integer.MAX_VALUE , it returns Integer.MAX_VALUE .

Returns an array containing all elements in this collection. If the


Object[] toArray()
collection guarantees iteration order, that order is maintained.

Returns an array containing all elements in this collection. If the


<T> T[] toArray(T[] a) collection fits in the specified array, it is returned. Otherwise, a new
array of the same runtime type is created and returned.

📘 java.util.List<E> Interface

Overview
The List interface provides an ordered collection — elements are arranged
according to their insertion order.

📚 Collection Framework in Java 5


Elements in a list can be accessed by a specific position using an integer
index.

List is zero-based, meaning the first element has an index of 0, just like
arrays.

Duplicate elements are allowed.

null values can also be inserted.

🔧 Inherited & Additional Methods in List Interface


The List interface includes all methods from the Collection interface and adds
additional methods specific to indexed access and ordering.

🧰 Additional Methods of List<E> :

Method Description

void add(int index, E Inserts the specified element at the specified position in this list
element) (optional operation).
boolean addAll(int
Inserts all elements from the specified collection into this list at the
index, Collection<?
extends E> c) specified position (optional operation).

E get(int index) Returns the element at the specified position in this list.

Returns the index of the first occurrence of the specified element,


int indexOf(Object o)
or -1 if the element is not present.

int lastIndexOf(Object Returns the index of the last occurrence of the specified element,
o) or -1 if the element is not present.

ListIterator<E> Returns a list iterator over the elements in this list, in proper
listIterator() sequence.
ListIterator<E>
Returns a list iterator, starting at the specified index.
listIterator(int index)

E remove(int index) Removes the element at the specified index (optional operation).

E set(int index, E Replaces the element at the specified index with the given element
element) (optional operation).

List<E> subList(int Returns a view of the portion of this list between fromIndex
fromIndex, int toIndex) (inclusive) and toIndex (exclusive).

📚 Collection Framework in Java 6


💡 Key Points:
Use List when order matters and duplicates are allowed.

Provides indexed access and modification of elements.

The most commonly used implementations of the List interface are:

ArrayList

LinkedList

Vector

Stack

Let me know if you'd like this as a PDF, formatted note sheet, or need a similar
explanation for Set , Map , or other collection interfaces.

📘 ArrayList Class in Java


The ArrayList class is a part of the Java Collection Framework and is used to
implement a dynamic array. Unlike standard arrays that have a fixed length, an
ArrayList can grow or shrink automatically at runtime based on the need.

Sometimes it's not possible to know the exact size of an array in advance. To
handle such situations, Java provides the ArrayList class.

An ArrayList object represents a resizable array.

Adding elements may increase the internal size.

Removing elements may shrink the size.

🧠 Key Characteristics of ArrayList


Elements are stored in sequential order.

Inserting an element in the middle shifts all subsequent elements.

Adding more elements than the current capacity causes:

A new array (approximately 1.5 times larger) to be allocated.

📚 Collection Framework in Java 7


All old elements to be copied to the new array.

Worst-case insertion is O(n) (due to shifting/copying), but average insertion is


constant time O(1).

ArrayList allows random access in constant time O(1).

🏗️ Constructors of ArrayList

Constructor Description

Constructs an empty list with an initial capacity of 10. Once this


ArrayList() capacity is reached, a new internal array is created using the formula:
newCapacity = (currentCapacity * 3 / 2) + 1

ArrayList(int
Constructs an empty list with the specified initial capacity.
initialCapacity)

ArrayList(Collection<? Constructs a list containing the elements of the specified collection,


extends E> c) in the order returned by the collection's iterator.

🧰 Commonly Used Methods in ArrayList

Method Description

void ensureCapacity(int Ensures that the ArrayList has at least the specified minimum
minCapacity) capacity.

Trims the capacity of the list to match the current number of


void trimToSize()
elements.

🔁 In addition to these methods, ArrayList also inherits all


methods from the List interface.

🧪 Example: Using ArrayList

import java.util.*;

public class Main {


public static void main(String[] args) {

📚 Collection Framework in Java 8


List<String> ls = new ArrayList<String>();

ls.add("A");
ls.add("B");
ls.add(1, "W"); // Inserts "W" at index 1 → [A, W, B]
ls.add("D");
ls.add("D"); // Duplicate element allowed
ls.add("T");
ls.add(null); // null allowed
ls.add(null); // Multiple nulls allowed

System.out.println(ls); // Output: [A, W, B, D, D, T, null, null]


}
}

📌 Note: All collection classes override the toString() method.


So, printing an ArrayList will display its elements inside square
brackets ([]) instead of printing the object's memory address.

🔁 Traversing an ArrayList

1️⃣ Using Traditional for Loop

for (int i = 0; i < ls.size(); i++) {


System.out.print(ls.get(i) + " ");
}
// Output: A W B D D T null null

2️⃣ Using Enhanced for-each Loop

📚 Collection Framework in Java 9


for (String element : ls) {
System.out.print(element + " ");
}
// Output: A W B D D T null null

java.util.Queue<T> Interface
Queueis a subinterface of Collection used to hold elements prior to
processing.

Typically, it follows FIFO (First-In-First-Out) order (but not mandatory).

For PriorityQueue , ordering is determined using a Comparator.

In any ordering, the head element is the one to be removed first, and new
elements are inserted at the tail.

🔧 Common Methods of Queue Interface


Method Description

boolean add(E Inserts the specified element into this queue if space is available. Throws
e) IllegalStateException if the queue is full.

Retrieves, but does not remove, the head of this queue. Throws an
E element()
exception if the queue is empty.

Retrieves and removes the head of this queue. Throws an exception if the
E remove()
queue is empty.

boolean offer(E Inserts the specified element into this queue if possible. Returns false if
e) space is unavailable.

Retrieves, but does not remove, the head of this queue, or returns null if
E peek()
empty.
E poll() Retrieves and removes the head of this queue, or returns null if empty.

📘 java.util.Deque<T> Interface

📚 Collection Framework in Java 10


Deque stands for Double-Ended Queue, pronounced “deck”.

It is a linear collection that supports insertion and removal at both ends.

🔧Collection
Methods Specific to Deque (in addition to Queue and
methods)
Method Description
void addFirst(E e) Inserts the element at the front. Throws IllegalStateException if full.
void addLast(E e) Inserts the element at the rear. Throws IllegalStateException if full.

Retrieves, but does not remove, the first element. Throws exception
E getFirst()
if empty.

Retrieves, but does not remove, the last element. Throws exception
E getLast()
if empty.
E removeFirst() Retrieves and removes the first element. Throws exception if empty.
E removeLast() Retrieves and removes the last element. Throws exception if empty.
boolean offerFirst(E e) Inserts the element at the front. Returns false if full.
boolean offerLast(E e) Inserts the element at the rear. Returns false if full.

Retrieves, but does not remove, the first element. Returns null if
E peekFirst()
empty.

Retrieves, but does not remove, the last element. Returns null if
E peekLast()
empty.
E pollFirst() Retrieves and removes the first element. Returns null if empty.
E pollLast() Retrieves and removes the last element. Returns null if empty.

Iterator<E> Returns an iterator over elements in reverse order (from tail to


descendingIterator() head).

📘 java.util.LinkedList<T> Class
A doubly-linked list implementation of both List and Deque interfaces.

🔄 Difference Between LinkedList and ArrayList

📚 Collection Framework in Java 11


Feature LinkedList ArrayList

Data Structure Uses doubly-linked list Uses resizable array

Constant time (O(1)) at known Slower (requires shifting


Insertion/Removal
positions elements)

Random access in constant


Access Sequential (slower random access)
time

Higher memory usage (stores data + Lower memory usage (stores


Memory
references) only data)

Finding point is O(n), operation is Finding is O(1), operation is


Insertion/Deletion
O(1) O(n)

🧪 Example:
File: Customer.java

public class Customer {


private String customerId;
private String customerName;
private double orderAmount;

public Customer(String customerId, String customerName, double orderAm


ount) {
this.customerId = customerId;
this.customerName = customerName;
this.orderAmount = orderAmount;
}

@Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + c
ustomerName + ", orderAmount=" + orderAmount + "]";
}
}

File: LinkedListDemo.java

📚 Collection Framework in Java 12


import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class LinkedListDemo {


public static void main(String[] args) {
List<Customer> customerList = new LinkedList<>();
Scanner sc = new Scanner(System.in);

char addAnotherCustomer = 'y';


do {
System.out.print("Enter customer id, name and order amount: ");
String customerId = sc.next();
String customerName = sc.next();
double orderAmount = sc.nextDouble();

Customer customer = new Customer(customerId, customerName, ord


erAmount);
customerList.add(customer);

System.out.print("Do you want to add another customer (y/n): ");


addAnotherCustomer = sc.next().charAt(0);
} while (addAnotherCustomer == 'y');

// Convert LinkedList to Array


Object customerArr[] = customerList.toArray();
for (Object customer : customerArr) {
System.out.println(customer);
}

sc.close();
}

📚 Collection Framework in Java 13


}

Output:

Enter customer id, name and order amount C001 Aman 2541
Do you want to add another customer (y/n) y
Enter customer id, name and order amount C002 Bajrag 5858
Do you want to add another customer (y/n) y
Enter customer id, name and order amount C003 Cindrella 14526
Do you want to add another customer (y/n) n

Customer [customerId=C001, customerName=Aman, orderAmount=2541.0]


Customer [customerId=C002, customerName=Bajrag, orderAmount=5858.0]
Customer [customerId=C003, customerName=Cindrella, orderAmount=14526.
0]

📘 java.util.Vector<T> Class
Vector is one of the implementation classes of List interface.

It is similar to ArrayList with the following differences:

Feature ArrayList Vector

Thread Safety Not synchronized Synchronized methods

Performance Faster (not thread-safe) Slower (thread-safe)

🧠 Synchronization is covered in Multithreading topics.


📘 java.util.Stack<T> Class

📚 Collection Framework in Java 14


Stack is a subclass of Vector.

Implements LIFO (Last-In-First-Out) data structure.

Inherits all methods of Vector and adds stack-specific methods.

🔧 Stack Methods
Method Description
E push(E item) Pushes an item onto the top of the stack.
E peek() Returns the item at the top without removing it.
E pop() Removes and returns the item at the top.

🧪 Example:
import java.util.Stack;

public class Main {


public static void main(String args[]) {
Stack<String> stack = new Stack<String>();

stack.push("A");
stack.push("B");
stack.push("C");
stack.push("D");
stack.push("E");

stack.peek(); // Returns top element (E)


stack.pop(); // Removes top element (E)

for (String s : stack) {


System.out.print(s + " ");
}
}

📚 Collection Framework in Java 15


}

Output:

ABCD

📘 java.util.Set<T> Interface
Overview
Set<T> is a subinterface of Collection .

It does not allow duplicate elements.

At most one null element can be added (though some implementations like
TreeSet do not allow null ).

Set interface has both ordered and unordered implementations.

It inherits all methods from the Collection interface but does not define any new
methods.

🔗 Set Hierarchy
java.util.Collection
|
java.util.Set
|
----------------------------
| | |
HashSet LinkedHashSet TreeSet

📚 Collection Framework in Java 16


📘 java.util.HashSet<T> Class

🔹 Characteristics
No guaranteed iteration order (order may change over time).

Allows null element.

Internally uses hashing to store elements.

Uses the hash code of elements to determine their storage position.

Backed by a HashMap internally.

🏗️ Constructors of HashSet

Constructor Description

Constructs an empty set with default capacity (16) and load factor
HashSet()
(0.75).

HashSet(Collection<? Constructs a set containing the elements from the specified


extends E> c) collection.

HashSet(int Constructs an empty set with the specified initial capacity and default
initialCapacity) load factor.
HashSet(int
initialCapacity, float Constructs an empty set with the given capacity and load factor.
loadFactor)

🧪 Example
import java.util.HashSet;
import java.util.Set;

public class HashSetDemo {


public static void main(String[] args) {
Set<String> hs = new HashSet<>();
hs.add("W");
hs.add("E");

📚 Collection Framework in Java 17


hs.add("Q");
hs.add("D");
hs.add("B");
hs.add("P");

System.out.println(hs);
System.out.println(hs.size());
}
}

Output:

[P, Q, B, D, E, W]
6

🔍 Note: The order of elements in a HashSet is not predictable.


📘 java.util.LinkedHashSet<T> Class

🔹 Characteristics
LinkedHashSet is a subclass of HashSet , but does not add new methods.

Maintains insertion order of elements.

Internally uses a hash table + doubly linked list to maintain order.

🧪 Updated Example Using LinkedHashSet

import java.util.LinkedHashSet;
import java.util.Set;

📚 Collection Framework in Java 18


public class LinkedHashSetDemo {
public static void main(String[] args) {
Set<String> hs = new LinkedHashSet<>();
hs.add("W");
hs.add("E");
hs.add("Q");
hs.add("D");
hs.add("B");
hs.add("P");

System.out.println(hs);
System.out.println(hs.size());
}
}

Output:

[W, E, Q, D, B, P]
6

✅ Use LinkedHashSet when you want no duplicates but want


to preserve insertion order.

📂 java.util.TreeSet<E> Class
▶️ Overview
Implements the Set interface.

📚 Collection Framework in Java 19


Stores elements in ascending order using a Red-Black Tree.

Provides guaranteed log(n) time complexity for operations like add , remove ,
and contains .

📊 Constructors of TreeSet
Constructor Description
TreeSet() Constructs an empty set, sorted according to the natural ordering.

TreeSet(Collection<? Constructs a set with elements from the specified collection, sorted
extends E> c) naturally.

TreeSet(Comparator<? Constructs an empty set sorted according to the provided


super E> comparator) comparator.

TreeSet(SortedSet<E> Constructs a set with the same elements and ordering as the given
s) sorted set.

📚 Example: TreeSet with LocalDate


import java.time.LocalDate;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {


public static void main(String[] args) {
Set<String> dateSet = new TreeSet<>();
dateSet.add("a");
dateSet.add("c");
dateSet.add("c");
dateSet.add("b");
dateSet.add("y");

System.out.println(dateSet);
}
}

📚 Collection Framework in Java 20


Output:

[a,b,c]

📌 java.util.Comparator<E> Interface
▶️ Purpose
Used to define custom sorting logic when natural ordering is not desired.

🔧 Methods
Method Description

Compares two objects. Returns negative if o1 < o2, zero if o1 == o2,


int compare(T o1, T o2)
positive if o1 > o2.
boolean equals(Object
Tests equality of comparators.
obj)

📚 Example: Sorting Mobiles by Price and then Model Number


public class Mobile {
private String modelNumber;
private Integer price;

public Mobile(String modelNumber, Integer price) {


this.modelNumber = modelNumber;
this.price = price;
}
}

public class MobileSort implements Comparator<Mobile> {


public int compare(Mobile m1, Mobile m2) {
if (m1.getPrice() > m2.getPrice()) return 1;
else if (m1.getPrice() < m2.getPrice()) return -1;

📚 Collection Framework in Java 21


return m1.getModelNumber().compareTo(m2.getModelNumber());
}
}

Set<Mobile> mobileSet = new TreeSet<>(new MobileSort());


mobileSet.add(new Mobile("A31", 22000));
mobileSet.add(new Mobile("Z31", 55000));
mobileSet.add(new Mobile("S31", 34000));
mobileSet.add(new Mobile("J33", 34000));

Output:

Mobile [Model Number A31, price = 22000]


Mobile [Model Number J33, price = 34000]
Mobile [Model Number S31, price = 34000]
Mobile [Model Number Z31, price = 55000]

📈 java.util.PriorityQueue<E> Class
▶️ Overview
A Queue implementation with priority-based ordering.

Elements ordered by natural ordering or via a Comparator.

Null elements are not permitted.

📊 Constructors
Constructor Description
PriorityQueue() Default capacity 11; natural ordering.
PriorityQueue(int
Specified capacity; natural ordering.
initialCapacity)

PriorityQueue(Comparator<?
Comparator-based priority queue.
super E>)

📚 Collection Framework in Java 22


Constructor Description
PriorityQueue(int,
Combines capacity and comparator.
Comparator)

PriorityQueue(Collection<?
Based on given collection.
extends E>)

PriorityQueue(PriorityQueue<?
Based on another PQ.
extends E>)

PriorityQueue(SortedSet<?
Based on a sorted set.
extends E>)

📚 Example: PriorityQueue with Comparable


public class CustomerOrder implements Comparable<CustomerOrder> {
private int orderId;
private double orderAmount;
private String customerName;

public int compareTo(CustomerOrder o) {


if (o.orderAmount > this.orderAmount) return 1;
else if (o.orderAmount < this.orderAmount) return -1;
return o.orderId < this.orderId ? 1 : -1;
}
// Getters, Setters, toString
}

Queue<CustomerOrder> customerOrders = new PriorityQueue<>();


customerOrders.add(new CustomerOrder(1, 100.0, "Aman"));
customerOrders.add(new CustomerOrder(3, 50.0, "Chetan"));
customerOrders.add(new CustomerOrder(2, 300.0, "Bhagat"));
while (!customerOrders.isEmpty())
System.out.println(customerOrders.poll());

Output:

📚 Collection Framework in Java 23


orderId:2, orderAmount:300.0, customerName:Bhagat
orderId:1, orderAmount:100.0, customerName:Aman
orderId:3, orderAmount:50.0, customerName:Chetan

📚 Example: Sorting by Customer Name using Comparator


public class CustomerOrderByName implements Comparator<CustomerOrder
>{
public int compare(CustomerOrder o1, CustomerOrder o2) {
return o1.getCustomerName().compareTo(o2.getCustomerName());
}
}

Queue<CustomerOrder> customerOrders = new PriorityQueue<>(new Custo


merOrderByName());
customerOrders.add(c1);
customerOrders.add(c2);
customerOrders.add(c3);
customerOrders.add(c4);

Output:

orderId:1, orderAmount:100.0, customerName:Aman


orderId:2, orderAmount:300.0, customerName:Bhagat
orderId:4, orderAmount:50.0, customerName:Chetan
orderId:3, orderAmount:50.0, customerName:Chetan

🔄 Comparable vs Comparator
Feature Comparable Comparator

Package java.lang java.util

Location of Logic Inside the class Outside the class

📚 Collection Framework in Java 24


Feature Comparable Comparator

Method int compareTo(Object o) int compare(Object o1, Object o2)

Sorting Logic Only one Multiple logic possible

The java.util.Map<K, V> Interface


Map interface is top in its own hierarchy. It does not have Collection interface as
its super interface.

It allows storage of values corresponding to unique keys.

A Map cannot have duplicate keys, and each key maps to a single value only.

Map supports three kinds of views:

1. A set of keys

2. A set of values

3. A set of key-value pairs

A Map cannot contain itself as a key but can contain itself as a value.

Some implementations restrict the types of keys or disallow null as a key.

Common Methods of Map


Method Description
void clear() Removes all of the mappings from the map.
boolean
containsKey(Object Returns true if this map contains a mapping for the specified key.
key)

boolean
Returns true if this map maps one or more keys to the specified
containsValue(Object
value)
value.

Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.
entrySet()

int hashCode() Returns the hash code value for this map.

📚 Collection Framework in Java 25


Method Description
boolean
Compares the specified object with this map for equality.
equals(Object o)

V get(Object key) Returns the value for the given key or null if not found.
boolean isEmpty() Returns true if this map contains no key-value mappings.
Set<K> keySet() Returns a Set view of the keys.
V put(K key, V value) Associates the specified value with the specified key.
void putAll(Map<?
extends K, ? extends Copies all mappings from the specified map.
V> m)

V remove(Object
Removes the mapping for a key, if present.
key)

int size() Returns the number of key-value mappings.


Collection<V>
Returns a Collection view of the values.
values()

The java.util.Map.Entry<K,V> Interface


A nested interface inside Map .

Required for iterating over entries.

Entries retrieved from entrySet() are valid only during that iteration.

Methods of Map.Entry
Method Description
boolean equals(Object o) Compares the specified object with this entry for equality.
K getKey() Returns the key.
V getValue() Returns the value.
int hashCode() Returns the hash code value for this map entry.
V setValue(V value) Replaces the value with the specified value.

The java.util.HashMap<K, V> Class


Implements Map<K,V> using a Hash Table.

📚 Collection Framework in Java 26


Allows null key and values.

Does not guarantee the order of entries.

Constructors of HashMap
Constructor Description
HashMap() Default initial capacity 16 and load factor 0.75.
HashMap(int
Sets specified capacity, default load factor.
initialCapacity)

HashMap(int initialCapacity,
Sets both capacity and load factor.
float loadFactor)

HashMap(Map<? extends
Initializes with the same mappings as the specified map.
K,? extends V> m)

Note: HashMap does not define any new methods. It


implements all methods of the Map interface.

Example

import java.util.*;

public class HashMapDemo {


public static void main(String[] args) {
Map<String, Integer> hm = new HashMap<>();
hm.put("All", 3);
hm.put("Is", 2);
hm.put("Well", 3);

System.out.println(hm);
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

hm.remove("Well");
hm.put("Well!", 4);

System.out.println("After Removal Map is : ");


Set<Map.Entry<String, Integer>> st = hm.entrySet();

📚 Collection Framework in Java 27


Iterator<Map.Entry<String, Integer>> itr = st.iterator();

while (itr.hasNext()) {
Map.Entry<String, Integer> entry = itr.next();
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
}
}

Output:

{All=3, Well=3, Is=2}


-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
After Removal Map is :
All:3 Is:2 Well!:4

The java.util.LinkedHashMap<K,V> Class


Provides linked list and hash table implementation of Map interface.

Maintains the insertion order of elements.

Constructors
Constructor Description

Constructs an empty insertion-ordered LinkedHashMap with default


LinkedHashMap()
capacity (16) and load factor (0.75).

LinkedHashMap(int Constructs an empty insertion-ordered LinkedHashMap with


initialCapacity) specified initial capacity and default load factor (0.75).
LinkedHashMap(int
Constructs an empty insertion-ordered LinkedHashMap with
initialCapacity, float
loadFactor)
specified capacity and load factor.

LinkedHashMap(int
initialCapacity, float Constructs a LinkedHashMap with specified capacity, load factor,
loadFactor, boolean and ordering mode.
accessOrder)

📚 Collection Framework in Java 28


Constructor Description
LinkedHashMap(Map<?
Constructs a LinkedHashMap with the same mappings as the
extends K, ? extends V>
m)
specified map.

Common Methods
Method Description

Comparator<? super K> Returns comparator used to order keys, or null if natural ordering
comparator() is used.
Set<Map.Entry<K,V>>
Returns a set view of the mappings.
entrySet()

K firstKey() Returns the lowest key.


SortedMap<K,V>
Returns portion of the map with keys less than toKey .
headMap(K toKey)

Set<K> keySet() Returns a set view of keys.


K lastKey() Returns the highest key.
SortedMap<K,V>
subMap(K fromKey, K Returns portion of the map within given range.
toKey)

SortedMap<K,V> Returns portion of the map with keys greater than or equal to
tailMap(K fromKey) fromKey .

Collection<V> values() Returns a collection view of values.

Updated Code Example:

Map<String, Integer> hm = new LinkedHashMap<>();

Output:

{All=3, Is=2, Well=3}


-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
After Removal Map is:
All:3 Is:2 Well!:4

The java.util.TreeMap<K,V> Class

📚 Collection Framework in Java 29


Red-Black Tree based NavigableMap implementation.

Entries sorted according to natural ordering or custom Comparator .

Constructors
Constructor Description
TreeMap() Constructs empty tree map using natural key ordering.
TreeMap(Comparator<?
Constructs tree map using the given comparator.
super K> comparator)

TreeMap(Map<? extends K, Constructs tree map with same mappings as specified map,
? extends V> m) using natural ordering.

TreeMap(SortedMap<K, ? Constructs tree map with mappings and ordering of the specified
extends V> m) sorted map.

Example: TreeMap with Custom Comparator


Student.java

public class Student {


private int rollNo;
private String name;
private int marks;

public Student(int rollNo, String name, int mark) {


this.rollNo = rollNo;
this.name = name;
this.marks = mark;
}

public int getRoll() { return rollNo; }


public void setRoll(int roll) { this.rollNo = roll; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getMarks() { return marks; }
public void setMarks(int marks) { this.marks = marks; }

📚 Collection Framework in Java 30


@Override
public String toString() {
return "Roll No: " + rollNo + " Name: " + name + " Marks: " + marks;
}
}

StudentMarksComp.java

import java.util.Comparator;

public class StudentMarksComp implements Comparator<Student> {


@Override
public int compare(Student s1, Student s2) {
if(s1.getMarks() > s2.getMarks()) return 1;
else if(s1.getMarks() < s2.getMarks()) return -1;
else return 0;
}
}

TreeMapDemo.java

import java.util.*;

public class TreeMapDemo {


public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>(new StudentMarksCom
p());
tm.put(new Student(10,"Ganesh",950), "Maharastra");
tm.put(new Student(12,"Surya",850), "Tamilnadu");
tm.put(new Student(15,"Venkat",920), "Telangana");
tm.put(new Student(16,"Dinesh",910), "Haryana");
tm.put(new Student(18,"Srinu",880), "Kerla");

for(Map.Entry<Student,String> me : tm.entrySet()) {
System.out.println("Toppers Student of State " + me.getValue() + " is "
+ me.getKey());

📚 Collection Framework in Java 31


}
}
}

Output:

Toppers Student of State Tamilnadu is Roll No: 12 Name: Surya Marks: 850
Toppers Student of State Kerla is Roll No: 18 Name: Srinu Marks: 880
Toppers Student of State Haryana is Roll No: 16 Name: Dinesh Marks: 910
Toppers Student of State Telangana is Roll No: 15 Name: Venkat Marks: 920
Toppers Student of State Maharastra is Roll No: 10 Name: Ganesh Marks: 950

📚 Collection Framework in Java 32

You might also like