java - 如何使用 Stream 将 Map of Map 转换为 Map of Object

标签 java java-stream

我有一个带有构建器的类(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/

相关文章:

java - fragment 子类中的 android getMenuInflater() - 无法解析方法

java - 以编程方式将按钮添加到 MapFragment/GoogleMap

java - 根据java 8中的同名条件将所有 HashMap 放在一起

用于过滤对象的 Java lambda 函数

java - 将 Java 8 Stream 与 ObjectMapper readValue 方法结合使用

java - 在数组中查找重复项

java - 如何在用户请求的特定日期和时间运行一组特定的java代码

java - JNA指针无效内存访问导致EXCEPTION_ACCESS_VIOLATION?

java - 并行计算集合的所有排列

java - 如何使用流将二维 int 数组转换为单个字符串?