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());
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.