In this post, I show you different ways to iterate over a HashMap in Java 8 lambda with an example.
- Iterating over a HashMap using Java 8 forEach and lambda.
- Iterating over the HashMap's entrySet using Java 8 forEach and lambda.
- Iterating over the HashMap's keySet.
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class IterateOverHashMap { public static void main(String[] args) { Map<String, Double> employeeSalary = new HashMap<>(); employeeSalary.put("David", 76000.00); employeeSalary.put("John", 120000.00); employeeSalary.put("Mark", 95000.00); employeeSalary.put("Steven", 134000.00); System.out.println("=== Iterating over a HashMap using Java 8 forEach and lambda ==="); employeeSalary.forEach((employee, salary) -> { System.out.println(employee + " => " + salary); }); System.out.println("\n=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ==="); employeeSalary.entrySet().forEach(entry -> { System.out.println(entry.getKey() + " => " + entry.getValue()); }); System.out.println("\n=== Iterating over the HashMap's keySet ==="); employeeSalary.keySet().forEach(employee -> { System.out.println(employee + " => " + employeeSalary.get(employee)); }); } }
Output
=== Iterating over a HashMap using Java 8 forEach and lambda ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
=== Iterating over the HashMap's keySet ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
Collections Examples
- Java LinkedHashMap Example
- Java HashSet Example
- Java LinkedList Example
- Java ArrayList Example
- Java Comparator Interface Example
- Java Comparable Interface Example
- Java IdentityHashMap Example
- Java WeakHashMap Example
- Java EnumMap Example
- Java CopyOnWriteArraySet Example
- Java EnumSet Class Example
- Guide to Java 8 forEach Method
- Different Ways to Iterate over a List in Java [Snippet]
- Different Ways to Iterate over a Set in Java [Snippet]
- Different Ways to Iterate over a Map in Java [Snippet]
- Iterate over TreeSet in Java Example
- Iterate over LinkedHashSet in Java Example
- Remove First and Last Elements of LinkedList in Java
- Iterate over LinkedList using an Iterator in Java
- Search an Element in an ArrayList in Java
- Iterate over ArrayList using Iterator in Java
- Remove Element from HashSet in Java
- Iterating over a HashSet using Iterator
- How To Remove Duplicate Elements From ArrayList In Java?
- Different Ways to Iterate over List, Set, and Map in Java
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course