HashMap Operations and Iteration
Demonstrates HashMap operations including put, get, merge, computeIfAbsent, and iteration with entrySet, keySet, and forEach methods.
Code
import java.util.*;
import java.util.function.*;
public class HashMapOperations {
public static void main(String[] args) {
Map<String, Integer> wordCount = new HashMap<>();
String[] words = "the quick brown fox jumps the lazy dog the fox".split(" ");
for (String word : words) {
wordCount.merge(word, 1, Integer::sum);
}
System.out.println("Word counts: " + wordCount);
Map<String, List<String>> grouped = new HashMap<>();
String[] items = {"apple:fruit", "carrot:veg", "banana:fruit", "celery:veg"};
for (String item : items) {
String[] parts = item.split(":");
grouped.computeIfAbsent(parts[1], k -> new ArrayList<>())
.add(parts[0]);
}
System.out.println("Grouped: " + grouped);
wordCount.forEach((word, count) -> {
if (count > 1) {
System.out.println("Repeated: " + word + " (" + count + ")");
}
});
int total = wordCount.values().stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Total words: " + total);
Map<String, Integer> sorted = new TreeMap<>(wordCount);
System.out.println("Sorted keys: " + sorted.keySet());
}
}How it works
HashMap Operations and Iteration is built around the class HashMapOperations and the function main.
Repetition is confined to for (String word : words) — the rest of the file is straight-line. The pipeline is a stream: source, lazy intermediate steps, one terminal collector.
Using it
The entry-point signature is public static void main(String[] args)
The run emits 5 labeled sections — Word counts:, Grouped:, Repeated:, Total words:, Sorted keys: — one per step.
Key statements
int total = wordCount.values().stream()
.mapToInt(Integer::intValue)
.sum();
Interactive Tools for This Topic
FAQ
- What does HashMap Operations and Iteration print when run?
- The script runs standalone; its 5 labeled outputs include `Word counts:`, `Grouped:`, `Repeated:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.