[英]Copy value from one hashmap to another
I have two hashmaps我有两个哈希图
Map<String, Employee> employees
Map<String, Address> address
and Employee and Address classes look as follows:和 Employee 和 Address 类如下所示:
class Employee {
String name,
String city
}
class Address {
String city
}
How can I copy city value from "address" hashmap to a city in Employee object of 'employees' hashmap if keys between these two hashmaps (employees and address) matches?如果这两个哈希图(员工和地址)之间的键匹配,如何将城市值从“地址”hashmap 复制到“员工”hashmap 的员工 object 中的城市?
I want to copy with functional java 8 declaratively without for loop.我想以声明方式使用功能 java 8 进行复制,而无需 for 循环。
You are actually trying to manipulate employees
map and if you just want to use lambdas for it, it can be done something like this assuming that the keys in both employees
and address
match:您实际上是在尝试操纵
employees
map 并且如果您只想使用 lambdas,则可以这样做,假设employees
和address
中的键都匹配:
address.entrySet().forEach(entry -> employees.get(entry.getKey()).setCity(entry.getValue().getCity()));
This can also be rewritten as这也可以重写为
address.forEach((key, val) -> employees.get(key).setCity(val.getCity()));
without making use of entrySet()
不使用
entrySet()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.