在本文中,我通过一个示例向您展示了在Java8 lambda中迭代HashMap的不同方法。
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));
});
}
}
=== 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
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2019/06/iterate-over-hashmap-java-using-lambda.html
内容来源于网络,如有侵权,请联系作者删除!