JAVA-COLLECTION_E-13
5 min readFeb 13, 2026
Basic HashMap Operations Program & concept
1️⃣ HashMapDemo1.java
package com.ravi.hash_map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapDemo1 {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Vanilla");
map.put(2, "Butterscotch");
map.put(3, "Chocolate");
map.put(4, "Cotton Candy");
System.out.println("HashMap entries are :");
System.out.println(map);
System.out.println("By using forEach method :");
map.forEach((key, value) ->
System.out.println("Key is :" + key + " Value is :" + value));
String icecream = map.get(4);
System.out.println(icecream);
icecream = map.getOrDefault(1, "This key is not existing");
System.out.println(icecream);
boolean hasKey = map.containsKey(3);
System.out.println("HashMap contains key 3: " + hasKey);
boolean hasValue = map.containsValue("Vanilla");
System.out.println("HashMap contains value 'Vanilla': " + hasValue);
map.remove(3);
System.out.println("After removing key 3 map is :" + map);
System.out.println("Iterating through Iterator :");
Iterator<Entry<Integer, String>> itr = map.entrySet().iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println("Iterating through HashMap:");
for (HashMap.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key is :" + entry.getKey() +
" Value is :" + entry.getValue());
}
int size = map.size();
System.out.println("Size of HashMap: " + size);
map.clear();
System.out.println("HashMap after clearing: " + map);
System.out.println("Is Map empty :" + map.isEmpty());
}
}2️⃣ HashMapDemo2.java
package com.ravi.hash_map;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class HashMapDemo2 {
public static void main(String[] args) {
HashMap<Integer, String> studentRecords = new HashMap<>();
studentRecords.put(101, "Scott");
studentRecords.put(102, "Smith");
studentRecords.put(103, "Martin");
studentRecords.put(104, "Aryan");
System.out.println("Student Records: " + studentRecords);
int searchId = 105;
String studentName = studentRecords.get(searchId);
Optional<String> ofNullable = Optional.ofNullable(studentName);
System.out.println(ofNullable.orElse("This id is not existing"));
System.out.println(studentRecords.put(103, "Rahul"));
System.out.println("Updated Records: " + studentRecords);
studentRecords.remove(104);
System.out.println("Records after removal: " + studentRecords);
int idToCheck = 101;
System.out.println("Does ID " + idToCheck + " exist? "
+ studentRecords.containsKey(idToCheck));
String nameToCheck = "Aryan";
System.out.println("Does name " + nameToCheck + " exist? "
+ studentRecords.containsValue(nameToCheck));
System.out.println("Iterating through records:");
for (Map.Entry<Integer, String> entry : studentRecords.entrySet()) {
System.out.println("ID: " + entry.getKey()
+ ", Name: " + entry.getValue());
}
studentRecords.clear();
System.out.println("All records cleared: " + studentRecords);
}
}3️⃣ HashMapDemo3.java
package com.ravi.hash_map;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
public class HashMapDemo3 {
public static void main(String[] args) {
HashMap<Integer, String> newmap1 = new HashMap<>();
HashMap<Integer, String> newmap2 = new HashMap<>();
newmap1.put(1, "OCPJP");
newmap1.put(2, "is");
newmap1.put(3, "best");
System.out.println("Values in newmap1: " + newmap1);
newmap2.put(4, "Exam");
System.out.println("Values in newmap2: " + newmap2);
System.out.println("After using putAll():");
newmap1.putAll(newmap2);
newmap1.forEach((k, v) -> System.out.println(k + " : " + v));
System.out.println("All the keys are :");
Set<Integer> keySet = newmap1.keySet();
System.out.println(keySet);
System.out.println("All the values are :");
Collection<String> values = newmap1.values();
System.out.println(values);
HashMap<String, String> map1 = new HashMap<>();
map1.put("ravi@gmail.com", "raj765");
map1.put("raj@gmail.com", "ravi0987");
map1.put("scott@gmail.com", "scott543");
System.out.println("From Map 1 :" + map1);
HashMap<String, String> map2 = new HashMap<>(map1);
System.out.println("From Map 2 :" + map2);
}
}4️⃣ HashMapDemo4.java (Using Record)
package com.ravi.hash_map;
import java.util.HashMap;
record Employee(Integer empId, String empName) { }
public class HashMapDemo4 {
public static void main(String[] args) {
Employee e1 = new Employee(101, "Aryan");
Employee e2 = new Employee(102, "Pooja");
Employee e3 = new Employee(101, "Aryan");
Employee e4 = e2;
HashMap<Employee, String> hm = new HashMap<>();
hm.put(e1, "Ameerpet");
hm.put(e2, "S R Nagar");
hm.put(e3, "Begumpet");
hm.put(e4, "Panjagutta");
hm.forEach((k, v) -> System.out.println(k + " : " + v));
}
}5️⃣ HashMapDemo5.java (Library Management)
package com.ravi.hash_map;
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo5 {
public static void main(String[] args) {
HashMap<String, Boolean> library = new HashMap<>();
library.put("Core Java", true);
library.put("Advanced Java", true);
library.put("HTML", false);
library.put("JavaScript", true);
System.out.println("Initial Library Status:");
library.forEach((k, v) -> System.out.println(k + " : " + v));
String bookToBorrow = "Advanced Java";
if (library.containsKey(bookToBorrow) && library.get(bookToBorrow)) {
library.put(bookToBorrow, false);
System.out.println(bookToBorrow + " has borrowed successfully...");
} else {
System.out.println(bookToBorrow + " book is not available for borrow");
}
String bookToReturn = "HTML";
if (library.containsKey(bookToReturn) && !library.get(bookToReturn)) {
library.put(bookToReturn, true);
System.out.println(bookToReturn + " has returned by the user");
} else {
System.out.println(bookToReturn + " is not in the library");
}
System.out.println("Final Library Status:");
for (Map.Entry<String, Boolean> entry : library.entrySet()) {
String status = entry.getValue() ? "Available" : "Borrowed";
System.out.println("Book: " + entry.getKey()
+ ", Status: " + status);
}
}
}Operations Covered
- put()
- forEach()
- get()
- getOrDefault()
- containsKey()
- containsValue()
- remove()
- entrySet() with Iterator
- Enhanced for-loop
- size()
- clear()
- isEmpty()Key Concepts
- HashMap<Integer,String> map = new HashMap<>();
- put() inserts entries
- Duplicate key replaces old value
- get(key) returns value
- getOrDefault(key, defaultValue) avoids null
- containsKey() checks key existence
- containsValue() checks value existence
- remove(key) deletes entry
- entrySet() used for iteration
- clear() removes all entries
- isEmpty() checks map empty or not================================================
2. STUDENT RECORD MANAGEMENT USING HASHMAP
=================================================Concepts Covered
- Storing studentId → studentName
- Searching by key
- Optional.ofNullable()
- Updating value
- Removing entry
- Iterating using entrySet()
- containsKey()
- containsValue()Important Points
- Optional.ofNullable(value).orElse("default")
→ Prevents NullPointerException- put(existingKey, newValue)
→ Updates value- remove(key)
→ Deletes record- containsKey(id)
→ Check student ID exists- containsValue(name)
→ Check student name exists
=================================================
3. keySet(), values(), putAll() – MAP INTERCONVERSION
=================================================Concepts Covered
- putAll()
- keySet()
- values()
- forEach()
- Copy constructorImportant Notes
- putAll(map2)
→ Merges map2 into map1- keySet()
→ Returns Set of keys- values()
→ Returns Collection of values- new HashMap<>(existingMap)
→ Creates copy of map
=================================================
4. HASHMAP WITH RECORD (IMMUTABLE KEY)
=================================================Concept
record Employee(Integer empId, String empName)Why Record?
- Record is immutable
- Automatically generates:
→ hashCode()
→ equals()
- Suitable for HashMap keyBehavior
If two Employee objects have same empId and empName:
→ Considered duplicate
→ Old value replaced=================================================
5. LIBRARY MANAGEMENT USING HASHMAP
=================================================Get Aman Verma’s stories in your inbox
Join Medium for free to get updates from this writer.
Scenario
HashMap<String, Boolean> library
Key → Book Name
Value → true (Available)
false (Borrowed)Operations Covered
- Borrow book
- Return book
- Check availability
- Final status displayLogic
Borrow:
if containsKey(book) AND value == true
→ set value = falseReturn:
if containsKey(book) AND value == false
→ set value = trueAvailability:
if value == true → Available
if value == false → Borrowed=================================================
6. WORD FREQUENCY COUNT USING HASHMAP
=================================================Logic
String text = "java is fun java is powerful java is great";
String[] words = text.split(" ");HashMap<String,Integer> wordCount = new HashMap<>();for each word:
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
Concept
getOrDefault(word,0)
→ If word not present → returns 0
→ Prevents null=================================================
7. computeIfAbsent() – JAVA 8
=================================================Definition
computeIfAbsent(K key, Function<K,V>)Behavior
- If key NOT present:
→ Compute value using function
→ Insert into map- If key present:
→ Return existing value- If function returns null:
→ Nothing inserted
=================================================
8. merge() – JAVA 8
=================================================Definition
merge(K key, V value, BiFunction<V,V,V>)Behavior
Case 1:
If key NOT present
→ Insert valueCase 2:
If key present
→ Combine old value and new valueCase 3:
If function returns null
→ Remove key from mapExample Logic:
map.merge("Apple", 10, (oldVal,newVal) -> oldVal + newVal);=================================================
9. computeIfAbsent() + merge() Combined Example
=================================================Example Concepts
map1.computeIfAbsent("A", key -> key.length());
map1.merge("B", 15, (oldVal,newVal) -> oldVal + newVal);- computeIfAbsent → Used to insert if missing
- merge → Used to update or combine values
=================================================
IMPORTANT EXAM POINTS
=================================================1) HashMap allows one null key
2) HashMap allows multiple null values
3) HashMap is NOT synchronized
4) Default capacity = 16
5) Default load factor = 0.75
6) Treeification occurs when bucket size > 8
7) Key must be immutable
8) hashCode() and equals() must follow contract
9) record is best option for HashMap key (Java 16+)








