Hackforge Academy

Category: React • Beginner

Published on 15 Feb 2026

Explanation

What is a Map? A Map<K, V> stores data in key–value pairs. • K → Key • V → Value Each key maps to exactly one value.
 Duplicate keys are not allowed, but duplicate values are allowed. #white- Example: 101 → "John" 102 → "Emma" 103 → "David"

Code Example


Explanation

Common Map Implementation classes: #white-HashMap: Fastest, most used #white-LinkedHashMap: Insertion order #white-TreeMap: Sorted order

Code Example

public static void main(String[] args) {
#white-  // Creating a HashMap
Map<Integer, String> students = new HashMap<>();
#white- // Adding elements
        students.put(101, "John");
        students.put(102, "Emma");
        students.put(103, "David");
System.out.println(students.get(101));
 
 
cont..

Explanation

Code Example

cont..
#white-// Removing element
students.remove(103);
#white-// Printing all entries
for (Map.Entry<Integer, String> entry : students.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
       }
}
#white-Output:
Student 101: John
Contains key 102? true
101 : John
102 : Emma

Explanation

#white-Sorted Map: Keys are automatically sorted.

Code Example

import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
Map<Integer, String> numbers = new TreeMap<>();
        numbers.put(3, "Three");
        numbers.put(1, "One");
        numbers.put(2, "Two");
        System.out.println(numbers);
    }}
#white-Output:
{1=One, 2=Two, 3=Three}

Explanation

#white-Iterating in Different Ways:

Code Example

Using keySet():
for (Integer key : students.keySet()) {
    System.out.println(key + " -> " + students.get(key));
}
Using values():
for (String value : students.values()) {
    System.out.println(value);
}
}
Using forEach (Java 8+):
students.forEach((key, value) ->
    System.out.println(key + " : " + value)
);

Explanation

Important Map Methods put(K, V) Insert key-value get(K) Get value by key remove(K) Delete by key containsKey(K) Check key containsValue(V) Check value size() Number of elements clear() Remove all

Code Example


Explanation

Word Frequency Program

Code Example

import java.util.HashMap;
import java.util.Map;
public class WordCount {
    public static void main(String[] args) {
String text = "apple banana apple orange banana apple";
String[] words = text.split(" ");

Map<String, Integer> wordCount = new HashMap<>();
cont..

Explanation

Code Example

cont..
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }
System.out.println(wordCount);
    }
}
Output:
{apple=3, banana=2, orange=1}

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.