How to transform HashMap to another HashMap using Java 8 Collectors toMap

Hello everyone, here we will show you how to convert HashMap<Integer, User> to another HashMap<Integer, UserDto> using Java 8 Collectors toMap. The Collectors.toMap returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.


Overview of components used in this example

Java Stream API

The Java Stream API provides a functional approach to processing collections of objects. The Stream in Java can be defined as a sequence of elements from a source Collection or Array. Most of the stream operations return a Stream. This helps create a chain of stream operations(stream pipe-lining). The streams also support the aggregate or terminal operations on the elements. for example, finding the minimum or maximum element or finding average etc...Stream operations can either be executed sequentially or parallel. when performed parallelly, it is called a parallel stream.

Collectors.toMap

The Collectors.toMap() method is a static method that returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

HashMap entrySet()

The Java HashMap entrySet() returns a set view of all the entries present in the hashmap.

Stream collect()

The Stream.collect() method is used to receive elements from a stream and store them in a collection.


Here is an example program to convert HashMap<Integer, User> to another HashMap<Integer, UserDto>,

User.java

public class User {

private String name;
private String email;
private String phone;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public User(String name, String email,
String phone) {

super();
this.name = name;
this.email = email;
this.phone = phone;
}

@Override
public String toString() {
return "User [name=" + name +
", email=" + email
+ ", phone=" + phone + "]";
}

}

 

UserDto.java

public class UserDto {

private Integer id;
private String name;
private String email;
private String phone;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public UserDto(Integer id, String name,
String email, String phone) {
super();
this.id = id;
this.name = name;
this.email = email;
this.phone = phone;
}

@Override
public String toString() {
return "UserDto [id=" + id + ", " + "name="
+ name + ", email=" + email +
", phone=" + phone + "]";
}
}


Mapper.java

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Mapper {

Map<Integer, User> users = new HashMap<>();

Mapper(Map<Integer, User> users) {
this.users = users;
}

public Map<Integer, UserDto> map() {

Map<Integer, UserDto> userDto = users.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(),
e -> new UserDto(e.getKey(),
e.getValue().getName(),
e.getValue().getEmail(),
e.getValue().getPhone())));

return userDto;
}
}


Driver.java

import java.util.HashMap;
import java.util.Map;

public class Driver {

public static void main(String[] args) {

User user = new User("dummy",
"dummygmail@gmail.gmail", "!91-879");
User user1 = new User("dummy2",
"dummygmail@gmail.gmail2", "!91-8792");
User user3 = new User("dummy3",
"dummygmail@gmail.gmail3", "!91-87923");

Map<Integer,User> users = new HashMap<Integer, User>();
users.put(1,user3);
users.put(2,user1);
users.put(3,user);

Mapper mapper = new Mapper(users);
System.out.println(mapper.map());
}
}

Output:


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example