10 HashMap Stream API Examples in Java
1. Iterate and Print Key-Value Pairs
Map map = [Link]("Apple", 3, "Banana", 5, "Cherry", 7);
[Link]().stream().forEach(entry -> [Link]([Link]() + " => "
+ [Link]()));
2. Filter Values Greater Than a Threshold
Map map = [Link]("A", 10, "B", 5, "C", 15, "D", 8); Map result =
[Link]().stream() .filter(entry -> [Link]() > 8)
.collect([Link]([Link]::getKey, [Link]::getValue));
[Link](result); // {A=10, C=15}
3. Filter Keys Starting With a Letter
Map map = [Link]("Apple", "Fruit", "Apricot", "Fruit", "Banana", "Fruit"); Map
result = [Link]().stream() .filter(entry -> [Link]().startsWith("A"))
.collect([Link]([Link]::getKey, [Link]::getValue));
[Link](result); // {Apple=Fruit, Apricot=Fruit}
4. Convert Keys to Uppercase
Map map = [Link]("apple", 1, "banana", 2); Map result = [Link]().stream()
.collect([Link](entry -> [Link]().toUpperCase(),
[Link]::getValue)); [Link](result); // {APPLE=1, BANANA=2}
5. Sort by Keys
Map map = [Link]("Banana", 2, "Apple", 5, "Cherry", 3); Map sorted =
[Link]().stream() .sorted([Link]())
.collect([Link]([Link]::getKey, [Link]::getValue, (e1, e2) -> e1,
LinkedHashMap::new)); [Link](sorted); // {Apple=5, Banana=2, Cherry=3}
6. Sort by Values
Map map = [Link]("A", 50, "B", 20, "C", 40); Map sorted = [Link]().stream()
.sorted([Link]()) .collect([Link]([Link]::getKey,
[Link]::getValue, (e1, e2) -> e1, LinkedHashMap::new));
[Link](sorted); // {B=20, C=40, A=50}
7. Convert to List of Keys
Map map = [Link]("X", 1, "Y", 2, "Z", 3); List keys =
[Link]().stream().collect([Link]()); [Link](keys); // [X,
Y, Z]
8. Find Maximum Value Entry
Map map = [Link]("John", 85, "Alice", 90, "Bob", 75); [Link] maxEntry =
[Link]().stream() .max([Link]()) .orElse(null);
[Link](maxEntry); // Alice=90
9. Count Keys Matching Condition
Map map = [Link]("Amazon", "Online", "Apple", "Tech", "Airtel", "Telecom"); long
count = [Link]().stream().filter(k -> [Link]("A")).count();
[Link](count); // 3
10. Merge Two Maps with Streams
Map map1 = [Link]("A", 1, "B", 2); Map map2 = [Link]("B", 3, "C", 4); Map merged =
[Link]([Link]().stream(), [Link]().stream())
.collect([Link]([Link]::getKey, [Link]::getValue, Integer::sum));
[Link](merged); // {A=1, B=5, C=4}