Practical 4
Assignment on Map Interface
Practical 4.1: Write a Java program using Map interface using Hash Map containing
list of items having keys and associated values and perform the following operations:
a. Add items in the map.
b. Remove items from the map
c. Search specific key from the map
d. Get value of the specified key
e. Insert map elements of one map in to other map.
f. Print all keys and values of the map.
Solution: -
package MAPIn;
import [Link].*;
public class MapAll
{
public static void main(String[] args)
{
// 1. Create a HashMap
Map<Integer, String> studentMap = new HashMap<>();
[Link]("=== Initial Map (empty) ===");
[Link]("[Link](): " + [Link]());
[Link]();
// 2. put() - add entries
[Link](101, "Sahil");
[Link](102, "Anika");
[Link](103, "Ravi");
[Link](104, "Priya");
[Link]("After put(): " + studentMap);
// 3. putIfAbsent() - won't overwrite existing key
[Link](102, "Anita"); // 102 exists -> no change
[Link](105, "Neha"); // 105 not present -> added
[Link]("\nAfter putIfAbsent(102,'Anita') and
putIfAbsent(105,'Neha'):");
[Link](studentMap);
// 4. putAll() - add all from another map
Map<Integer, String> extra = new HashMap<>();
[Link](106, "Rohit");
[Link](107, "Meera");
Page. 1 RG, MCA sem 1 AJ Manual
[Link](extra);
[Link]("\nAfter putAll(extra): " + studentMap);
// 5. get() and getOrDefault()
[Link]("\nName for key 103: " + [Link](103));
[Link]("Name for key 999 (getOrDefault): " +
[Link](999, "Unknown"));
// 6. containsKey() and containsValue()
[Link]("\nContains key 104? " + [Link](104));
[Link]("Contains value 'Neha'? " +
[Link]("Neha"));
// 7. computeIfAbsent() - useful for lazy insertion (e.g., default generation)
[Link](108, k -> "Student" + k); // adds 108 ->
"Student108"
[Link]("\nAfter computeIfAbsent(108): " + studentMap);
// 8. replace(key, value) and replace(key, oldValue, newValue)
[Link](101, "Sahil Kumar"); // simple replace
boolean replaced = [Link](102, "Anika", "Anika Sharma"); //
conditional replace
[Link]("\nAfter replace operations:");
[Link]("Replaced conditional (102 from 'Anika' to 'Anika Sharma')?
" + replaced);
[Link](studentMap);
// 9. remove(key) and remove(key, value)
String removedValue = [Link](107); // removes key 107
boolean removedCond = [Link](106, "Rohit"); // removes only if
value matches
[Link]("\nAfter removals:");
[Link]("Removed value for key 107: " + removedValue);
[Link]("Conditional removal of (106,'Rohit') succeeded? " +
removedCond);
[Link](studentMap);
// 10. Iteration: keySet(), values(), entrySet()
[Link]("\nIterate keys (keySet):");
for (Integer key : [Link]()) {
[Link](key + " ");
}
[Link]("\n\nIterate values (values):");
for (String name : [Link]()) {
Page. 2 RG, MCA sem 1 AJ Manual
[Link](name + " ");
}
[Link]("\n\nIterate entries (entrySet):");
for ([Link]<Integer, String> entry : [Link]())
{
[Link]("Key = " + [Link]() + ", Value = " +
[Link]());
}
// 11. size(), isEmpty()
[Link]("\nSize of map: " + [Link]());
[Link]("Is map empty? " + [Link]());
// 12. replaceAll() - modify all values (for demonstration)
[Link]((k, v) -> v + " [ID:" + k + "]");
[Link]("\nAfter replaceAll (append ID to names):");
[Link](studentMap);
// 13. Convert to TreeMap for sorted order by key
Map<Integer, String> sortedMap = new TreeMap<>(studentMap);
[Link]("\nTreeMap (sorted by key): " + sortedMap);
// 14. clear()
[Link]();
[Link]("\nAfter clear(), isEmpty(): " + [Link]());
}
}
Output:-
=== Initial Map (empty) ===
[Link](): true
After put(): {101=Sahil, 102=Anika, 103=Ravi, 104=Priya}
After putIfAbsent(102,'Anita') and putIfAbsent(105,'Neha'):
{101=Sahil, 102=Anika, 103=Ravi, 104=Priya, 105=Neha}
After putAll(extra): {101=Sahil, 102=Anika, 103=Ravi, 104=Priya, 105=Neha,
106=Rohit, 107=Meera}
Name for key 103: Ravi
Name for key 999 (getOrDefault): Unknown
Contains key 104? true
Contains value 'Neha'? true
Page. 3 RG, MCA sem 1 AJ Manual
After computeIfAbsent(108): {101=Sahil, 102=Anika, 103=Ravi, 104=Priya,
105=Neha, 106=Rohit, 107=Meera, 108=Student108}
After replace operations:
Replaced conditional (102 from 'Anika' to 'Anika Sharma')? true
{101=Sahil Kumar, 102=Anika Sharma, 103=Ravi, 104=Priya, 105=Neha, 106=Rohit,
107=Meera, 108=Student108}
After removals:
Removed value for key 107: Meera
Conditional removal of (106,'Rohit') succeeded? true
{101=Sahil Kumar, 102=Anika Sharma, 103=Ravi, 104=Priya, 105=Neha,
108=Student108}
Iterate keys (keySet):
101 102 103 104 105 108
Iterate values (values):
Sahil Kumar Anika Sharma Ravi Priya Neha Student108
Iterate entries (entrySet):
Key = 101, Value = Sahil Kumar
Key = 102, Value = Anika Sharma
Key = 103, Value = Ravi
Key = 104, Value = Priya
Key = 105, Value = Neha
Key = 108, Value = Student108
Size of map: 6
Is map empty? false
After replaceAll (append ID to names):
{101=Sahil Kumar [ID:101], 102=Anika Sharma [ID:102], 103=Ravi [ID:103],
104=Priya [ID:104], 105=Neha [ID:105], 108=Student108 [ID:108]}
TreeMap (sorted by key): {101=Sahil Kumar [ID:101], 102=Anika Sharma [ID:102],
103=Ravi [ID:103], 104=Priya [ID:104], 105=Neha [ID:105], 108=Student108
[ID:108]}
After clear(), isEmpty(): true
Practical 4.2: Using TreeMap (Employee IDs and Salaries)
Solution: -
package MAPIn;
import [Link].*;
public class EmpTreeMap
{
public static void main(String[] args)
{
// Create a TreeMap (stores keys in sorted order)
TreeMap<Integer, Double> employeeSalary = new TreeMap<>();
Page. 4 RG, MCA sem 1 AJ Manual
// Add employee IDs and salaries
[Link](103, 55000.0);
[Link](101, 48000.0);
[Link](104, 60000.0);
[Link](102, 50000.0);
// Display all employee records (automatically sorted by ID)
[Link]("Employee Salary Records (Sorted by ID):");
for ([Link]<Integer, Double> entry : [Link]())
{
[Link]("Employee ID: " + [Link]() + " | Salary: ₹" + [Link]());
}
// Update salary for an existing employee
int empIdToUpdate = 102;
if ([Link](empIdToUpdate))
{
[Link](empIdToUpdate, 52000.0);
[Link]("\nUpdated Salary for Employee ID " + empIdToUpdate + ": ₹" +
[Link](empIdToUpdate));
} else {
[Link]("\nEmployee ID " + empIdToUpdate + " not found.");
}
// Display updated records
[Link]("\nUpdated Employee Salary Records:");
for ([Link]<Integer, Double> entry: [Link]())
{
[Link]("Employee ID: " + [Link]() + " | Salary: ₹" + [Link]());
}
}
}
Output: -
Employee Salary Records (Sorted by ID):
Employee ID: 101 | Salary: ₹48000.0
Employee ID: 102 | Salary: ₹50000.0
Employee ID: 103 | Salary: ₹55000.0
Employee ID: 104 | Salary: ₹60000.0
Updated Salary for Employee ID 102: ₹52000.0
Updated Employee Salary Records:
Employee ID: 101 | Salary: ₹48000.0
Employee ID: 102 | Salary: ₹52000.0
Employee ID: 103 | Salary: ₹55000.0
Employee ID: 104 | Salary: ₹60000.0
Page. 5 RG, MCA sem 1 AJ Manual
Practical 4.3: Using LinkedHashMap (Subjects and Marks)
Solution: -
package MAPIn;
import [Link].*;
public class SubLinkHM
{
public static void main(String[] args)
{
// Create a LinkedHashMap (maintains insertion order)
LinkedHashMap<String, Integer> subjectMarks = new LinkedHashMap<>();
// Add subjects and marks
[Link]("Mathematics", 85);
[Link]("Science", 90);
[Link]("English", 78);
[Link]("Computer", 92);
[Link]("History", 80);
// Display all subjects and marks in insertion order
[Link]("Subject Marks Record (Using keySet):");
for (String subject : [Link]())
{
[Link]("Subject: " + subject + " | Marks: " + [Link](subject));
}
// Calculate average marks
int totalMarks = 0;
for (int mark : [Link]())
{
totalMarks += mark;
}
double average = (double) totalMarks / [Link]();
[Link]("\nTotal Subjects: " + [Link]());
[Link]("Average Marks: " + average);
}
}
Output: -
Subject Marks Record (Using keySet):
Subject: Mathematics | Marks: 85
Subject: Science | Marks: 90
Subject: English | Marks: 78
Subject: Computer | Marks: 92
Subject: History | Marks: 80
Total Subjects: 5
Average Marks: 85.0
Page. 6 RG, MCA sem 1 AJ Manual
Exercise
1. Write a Java program to copy all mappings from the specified map to another map.
2. Write a Java program to test if a map contains a mapping for the specified value.
3. Write a Java program to associate the specified value with the specified key in a Tree
Map.
4. Write a Java program to search for a value and key in a Tree Map.
5. City Distance Finder using HashMap
o Use a `HashMap` where the key is a city name and the value is its distance
from a reference point (e.g., your current location).
o Add multiple cities and their distances.
o Retrieve and display the distance for a specific city when searched.
o Display all cities within a certain distance.
6. Employee Directory using LinkedHashMap
o Create an `Employee` class with fields like `id`, `name`, and `department`.
o Use a `LinkedHashMap` to store employees, ensuring they are displayed in
the order they were added.
o Add operations to add, remove, and search for an employee.
o Display all employees in insertion order.
Page. 7 RG, MCA sem 1 AJ Manual