Category: java
Map & Streams
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.
Example:
101 → "John"
102 → "Emma"
103 → "David"
Code:
Explanation
Common Map Implementation classes:
HashMap:
Fastest, most used
LinkedHashMap:
Insertion order
TreeMap:
Sorted order
Code:
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:
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
Sorted Map:
Keys are automatically sorted.
Code:
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
Iterating in Different Ways:
Code:
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:
Explanation
Word Frequency Program
Code:
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:
cont..
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
System.out.println(wordCount);
}
}
Output:
{apple=3, banana=2, orange=1}