我有一个带有构建器的类(class):
Student.builder().name("Name").email("Email").phone("Phone").build();
class Student {
String name;
String email;
String phone;
}
我有一个Map<String, Map<String, String>
转换为 Map<String, Student>
("GroupA", ("name", "Steve"))
("GroupA", ("email", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafdecffecc9eee4e8e0e5a7eae6e4" rel="noreferrer noopener nofollow">[email protected]</a>"))
("GroupA", ("phone", "111-222-3333"))
("GroupB", ("name", "Alice"))
("GroupB", ("email", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="badbd6d3d9dffaddd7dbd3d694d9d5d7" rel="noreferrer noopener nofollow">[email protected]</a>"))
("GroupB", ("phone", "111-222-4444"))
("GroupC", ("name", "Bobby"))
("GroupC", ("email", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36545954544f76515b575f5a1855595b" rel="noreferrer noopener nofollow">[email protected]</a>"))
("GroupC", ("phone", "111-222-5555"))
我正在尝试使用 Stream 使代码更简洁,但不确定如何实现这一点。我用普通的 Java 代码得到了什么
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()
));
它是如何工作的:
您获取映射的条目集,将其流式传输,然后使用 Collectors.toMap
收集器收集到新映射,该收集器接受两个用于创建键和值的函数(键映射器和值映射器)新 map 的值。您需要原始 map 中的 key ,因此只需传递方法引用 Map.Entry::getKey
即可从条目中获取 key 。要创建新值,您需要传递一个函数,该函数接受 Map.Entry e
并从中创建一个新的 Student
关于java - 如何使用 Stream 将 Map of Map 转换为 Map of Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743460/