Java 如何使用流将地图的地图转换为对象的地图
我有一个建筑工人的班级:Java 如何使用流将地图的地图转换为对象的地图,java,java-stream,Java,Java Stream,我有一个建筑工人的班级: Student.builder().name("Name").email("Email").phone("Phone").build(); 我有一张地图试试这个: Map<String, Student> newStudentMap = studentMap.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, e -> Student.builder()
Student.builder().name("Name").email("Email").phone("Phone").build();
我有一张地图试试这个:
Map<String, Student> newStudentMap = studentMap.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> Student.builder()
.name(e.getValue().get("name"))
.email(e.getValue().get("email"))
.phone(e.getValue().get("phone"))
.build()
));
Map newStudentMap=studentMap.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e->Student.builder()
.name(e.getValue().get(“name”))
.email(e.getValue().get(“email”))
.phone(e.getValue().get(“phone”))
.build()
));
工作原理:
获取地图的条目集,将其流化,然后使用收集器收集到新地图。toMap
收集器接受两个函数(键映射器和值映射器),用于为新地图创建键和值。您需要原始映射中的密钥,因此只需传递方法引用map.Entry::getKey
,即可从条目中获取密钥。要创建一个新值,您需要传递一个函数,该函数接受Map.Entry e
,并从中创建一个新的Student
,我认为您的地图已经包含了一个问题。您不应该这样存储数据。如果你从一张地图开始,那就足够了。以你这样做的方式,你不知道哪封邮件属于哪一个名字等等。。。然后,您只需调用构造函数……除非某个映射或对象实际上是Student的实例,否则您希望如何从该映射或对象中生成Student?为什么您的映射有多个具有相同键(“GroupA”)的条目?抱歉,复制和粘贴问题。我会修好的。我还添加了更多信息。通过转换,你的意思是创建一个新的地图实例?因为您无法从map更改旧映射的数据类型
("GroupA", ("name", "Steve"))
("GroupA", ("email", "steve@gmail.com"))
("GroupA", ("phone", "111-222-3333"))
("GroupB", ("name", "Alice"))
("GroupB", ("email", "alice@gmail.com"))
("GroupB", ("phone", "111-222-4444"))
("GroupC", ("name", "Bobby"))
("GroupC", ("email", "bobby@gmail.com"))
("GroupC", ("phone", "111-222-5555"))
Map<String, Student> newStudentMap = new HashMap<>();
for (Map.Entry<String, Map<String, String>> entry : studentMap.entrySet()) {
Map<String, String> value = entry.getValue();
Student student = Student.builder()
.name(value.get("name"))
.email(value.get("email")))
.phone(value.get("phone"))
.build();
newStudentMap.put(entry.getKey(), student);
}
Map<String, Student> newStudentMap = studentMap.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> Student.builder()
.name(e.getValue().get("name"))
.email(e.getValue().get("email"))
.phone(e.getValue().get("phone"))
.build()
));