domingo, 31 de enero de 2021

Convert HashMap objects using Lambda expression

Scenario

We need to transform a HashMap that contains a String and an object into another HashMap that keeps that information but mapping the object to a different one. Let's imagine that we have a set of Person entities included in a HashMap and we want at some point to transform them into the equivalent DTOs, to do so we can use a simple Lambda expression to get the work done:

Solution

A simple Person entity:

@Getter
@AllArgsConstructor
public class Person {

    private final String name;
    private final String lastName;
    private final int age;
    private final String address;

    public PersonDTO toDto(){
        return new PersonDTO(name, lastName, age, address);
    }
}

Our target DTO

@Getter
@AllArgsConstructor
public class PersonDTO {

    private final String name;
    private final String lastName;
    private final int age;
    private final String address;
}

Now, to go through the a set of Person included in a HashMap and transform them into the correspondent DTOs we can use the toMap included with the java.util.stream.Collectors and define the value for both the key and the value using our toDTO() method to transform each entity.

Map<String, PersonDTO> personDTOMap = personMap.entrySet()
        .stream()
        .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().toDto()));

In a complete example:

@Test
void map_a_Map_to_a_Map_and_dont_get_mad(){
    Map<String, Person> personMap = new HashMap<>();
    personMap.put("01", new Person("John", "Doe", 41, "Baker Street"));
    personMap.put("02", new Person("Rose", "Smith", 39, "Helm Street"));

    Map<String, PersonDTO> personDTOMap = personMap.entrySet()
            .stream()
            .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().toDto()));

    Assertions.assertThat(personDTOMap).size().isEqualTo(2);
    Assertions.assertThat(personDTOMap.entrySet()
            .stream()
            .filter(entry -> entry.getKey().equals("01"))
            .findFirst()
            .orElseThrow()
            .getValue()
            .getName())
            .isEqualTo("John");
}

No hay comentarios:

Using flatMap to extract nested elements from a List

Scenario We need to extract the nested elements from a list of lists based on levels. To do so we can use the flatMap functionality from ...