hieu
hieu

Reputation: 63

How to convert a Map of Map to Map of Object using Stream

I have an class with a Builder:

Student.builder().name("Name").email("Email").phone("Phone").build();
class Student {
    String name;
    String email;
    String phone; 
}

I have a Map<String, Map<String, String> to convert to Map<String, Student>

("GroupA", ("name", "Steve"))
("GroupA", ("email", "[email protected]"))
("GroupA", ("phone", "111-222-3333"))
("GroupB", ("name", "Alice"))
("GroupB", ("email", "[email protected]"))
("GroupB", ("phone", "111-222-4444"))
("GroupC", ("name", "Bobby"))
("GroupC", ("email", "[email protected]"))
("GroupC", ("phone", "111-222-5555"))

I am trying to using Stream to make the code a bit cleaner but not sure how to accomplish this. What I have with normal Java code

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);
}

Upvotes: 2

Views: 385

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8481

Try this:

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()
    ));

How it works:

You take the entry set of your map, stream it and then collect to a new map using the Collectors.toMap collector that accepts two functions (key mapper and value mapper) used to create keys and values for a new map. You need the key from your original map, so you simply pass the method reference Map.Entry::getKey to take the key from the entry. And to create a new value you pass a function that takes Map.Entry e and creates a new Student from it

Upvotes: 2

Related Questions