Java中使用Lambda遍历HashMap

x33g5p2x  于2022-10-16 转载在 Java  
字(1.5k)|赞(0)|评价(0)|浏览(1055)

在本文中,我通过一个示例向您展示了在Java8 lambda中迭代HashMap的不同方法。

  • 使用Java 8forEach和lambda迭代HashMap。
  • 使用Java 8forEachlambda迭代HashMap的entrySet。
  • 迭代HashMap的keySet

Java 8中迭代HashMap

  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;
  5. public class IterateOverHashMap {
  6. public static void main(String[] args) {
  7. Map<String, Double> employeeSalary = new HashMap<>();
  8. employeeSalary.put("David", 76000.00);
  9. employeeSalary.put("John", 120000.00);
  10. employeeSalary.put("Mark", 95000.00);
  11. employeeSalary.put("Steven", 134000.00);
  12. System.out.println("=== Iterating over a HashMap using Java 8 forEach and lambda ===");
  13. employeeSalary.forEach((employee, salary) -> {
  14. System.out.println(employee + " => " + salary);
  15. });
  16. System.out.println("\n=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===");
  17. employeeSalary.entrySet().forEach(entry -> {
  18. System.out.println(entry.getKey() + " => " + entry.getValue());
  19. });
  20. System.out.println("\n=== Iterating over the HashMap's keySet ===");
  21. employeeSalary.keySet().forEach(employee -> {
  22. System.out.println(employee + " => " + employeeSalary.get(employee));
  23. });
  24. }
  25. }

输出

  1. === Iterating over a HashMap using Java 8 forEach and lambda ===
  2. David => 76000.0
  3. John => 120000.0
  4. Mark => 95000.0
  5. Steven => 134000.0
  6. === Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===
  7. David => 76000.0
  8. John => 120000.0
  9. Mark => 95000.0
  10. Steven => 134000.0
  11. === Iterating over the HashMap's keySet ===
  12. David => 76000.0
  13. John => 120000.0
  14. Mark => 95000.0
  15. Steven => 134000.0

相关文章

最新文章

更多