Collect and Convert Objects using Lambda Expression in Java 8

You may also like to read:

Introduction

In this tutorial, I will show you how you are going to collect and convert objects using lambda expression in Java 8 stream API. We will collect objects and map to another custom objects using Java 8 stream API with the help of Lambda Expression.

Suppose you have entity classes generated from your database tables and after fetching data from database tables you want to apply some logic and want to map to custom Data Transfer Objects.

So here is the example which shows how to do that. This example does not use any database here.

Prerequisites

Java 1.8, Eclipse Neon

Example and Source Code

Create below entity classes. Ideally, entity classes should be mapped to database tables. But for our example we will assume that we are working on entity classes.

package com.jeejava.java8.stream;

public class PersonEntity {

	private int id;
	private String name;
	private String email;

	public PersonEntity() {
	}

	public PersonEntity(int id, String name, String email) {
		this.id = id;
		this.name = name;
		this.email = email;
	}

	// getters and setters

}

The below class holds a list of PersonEntity objects.

package com.jeejava.java8.stream;

import java.util.List;

public class PersonGroupEntity {

	private String grpName;
	private List<PersonEntity> persons;

	public PersonGroupEntity() {
	}

	public PersonGroupEntity(String grpName, List<PersonEntity> persons) {
		this.grpName = grpName;
		this.persons = persons;
	}
     
        //getters and setters

}

Creating DTO Class

Create DTO classes so that Entity objects will be mapped into DTO objects using Java 8 Lambda Expression.

package com.jeejava.java8.stream;

public class PersonDto {

	private int id;
	private String firstName;
	private String lastName;
	private String emailAddress;

	//getters and setters

	@Override
	public String toString() {
		return "PersonDto [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailAddress="
				+ emailAddress + "]";
	}

}

Similarly the below class will hold a list of PersonDto objects.

package com.jeejava.java8.stream;

import java.util.ArrayList;
import java.util.List;

public class PersonGroupDto {

	private String groupName;
	private List<PersonDto> persons;

	public String getGroupName() {
		return groupName;
	}

	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}

	public List<PersonDto> getPersons() {
		if (persons == null) {
			persons = new ArrayList<>();
		}
		return persons;
	}

	public void setPersons(List<PersonDto> persons) {
		this.persons = persons;
	}

	@Override
	public String toString() {
		return "PersonGroupDto [groupName=" + groupName + ", persons=" + persons + "]";
	}

}

Converting using Lambda

Now create below main class that will be used to convert using lambda expression and test the example using dummy values.

package com.jeejava.java8.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectListOfObjectsUsingStream {

	public static void main(String[] args) {

		PersonEntity pe1 = new PersonEntity(1000, "Soumitra roy", "contact@roytuts.com");
		PersonEntity pe2 = new PersonEntity(1001, "arup chatterjee", "arup@chatterjee.com");
		PersonEntity pe3 = new PersonEntity(1002, "Souvik Sanyal", "souvik@sanyal.com");
		PersonEntity pe4 = new PersonEntity(1003, "suman Mukherjee", "suman@mukherjee.com");
		PersonEntity pe5 = new PersonEntity(1004, "soumitra sarkar", "contact@roytuts.com");
		PersonEntity pe6 = new PersonEntity(1005, "Anjel Ghosh", "anjel@ghosh.com");
		PersonEntity pe7 = new PersonEntity(1006, "suman Pandit", "suman@pandit.com");
		PersonEntity pe8 = new PersonEntity(1007, "Ranjit pandit", "ranjit@pandit.com");
		PersonEntity pe9 = new PersonEntity(1008, "TK pal", "tk@pal.com");
		PersonEntity pe10 = new PersonEntity(1009, "Abhisekh paul", "abhisekh@paul.com");
		PersonEntity pe11 = new PersonEntity(1010, "Sumanjit raut", "sumanjit@raut.com");

		PersonGroupEntity pg1 = new PersonGroupEntity("Product", new ArrayList<PersonEntity>(Arrays.asList(pe9)));
		PersonGroupEntity pg2 = new PersonGroupEntity("Service",
				new ArrayList<PersonEntity>(Arrays.asList(pe1, pe2, pe3, pe4, pe5, pe7, pe10, pe11)));
		PersonGroupEntity pg3 = new PersonGroupEntity("Solution", new ArrayList<PersonEntity>(Arrays.asList(pe6)));
		PersonGroupEntity pg4 = new PersonGroupEntity("Teaching", new ArrayList<PersonEntity>(Arrays.asList(pe8)));
		PersonGroupEntity pg5 = new PersonGroupEntity("Core", null);

		List<PersonGroupEntity> personGroupEntities = new ArrayList<>(Arrays.asList(pg1, pg2, pg3, pg4, pg5));

		List<PersonGroupDto> personGroupDtos = personGroupEntities.stream().map(pg -> {
			PersonGroupDto personGroupDto = new PersonGroupDto();
			personGroupDto.setGroupName(pg.getGrpName());
			if (pg.getPersons() != null) {
				List<PersonDto> personDtos = pg.getPersons().stream().map(p -> {
					PersonDto personDto = new PersonDto();
					personDto.setId(p.getId());
					String[] fullName = splitNamesInitCharCapitalize(p.getName());
					personDto.setFirstName(fullName[0]);
					personDto.setLastName(fullName[1]);
					personDto.setEmailAddress(p.getEmail());
					return personDto;
				}).collect(Collectors.toList());
				personGroupDto.setPersons(personDtos);
			} else {
				personGroupDto.setPersons(new ArrayList<>());
			}
			return personGroupDto;
		}).collect(Collectors.toList());

		personGroupDtos.forEach(pg -> System.out.println(pg));
	}

	private static String[] splitNamesInitCharCapitalize(String name) {
		String[] splits = name.split("\\s");
		String firstNameInitChar = splits[0].substring(0, 1).toUpperCase();
		String lastNameInitChar = splits[1].substring(0, 1).toUpperCase();
		String[] fullName = new String[] { firstNameInitChar + splits[0].substring(1),
				lastNameInitChar + splits[1].substring(1) };
		return fullName;
	}

}

Output

PersonGroupDto [groupName=Product, persons=[PersonDto [id=1008, firstName=TK, lastName=Pal, emailAddress=tk@pal.com]]]
PersonGroupDto [groupName=Service, persons=[PersonDto [id=1000, firstName=Soumitra, lastName=Roy, emailAddress=contact@roytuts.com], PersonDto [id=1001, firstName=Arup, lastName=Chatterjee, emailAddress=arup@chatterjee.com], PersonDto [id=1002, firstName=Souvik, lastName=Sanyal, emailAddress=souvik@sanyal.com], PersonDto [id=1003, firstName=Suman, lastName=Mukherjee, emailAddress=suman@mukherjee.com], PersonDto [id=1004, firstName=Soumitra, lastName=Sarkar, emailAddress=contact@roytuts.com], PersonDto [id=1006, firstName=Suman, lastName=Pandit, emailAddress=suman@pandit.com], PersonDto [id=1009, firstName=Abhisekh, lastName=Paul, emailAddress=abhisekh@paul.com], PersonDto [id=1010, firstName=Sumanjit, lastName=Raut, emailAddress=sumanjit@raut.com]]]
PersonGroupDto [groupName=Solution, persons=[PersonDto [id=1005, firstName=Anjel, lastName=Ghosh, emailAddress=anjel@ghosh.com]]]
PersonGroupDto [groupName=Teaching, persons=[PersonDto [id=1007, firstName=Ranjit, lastName=Pandit, emailAddress=ranjit@pandit.com]]]
PersonGroupDto [groupName=Core, persons=[]]

Source Code

You can download source code.

Thanks for reading.

Collect and Convert Objects using Lambda Expression in Java 8
I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger and writing blogs is my passion. Connect me on Roy Tutorials | Twitter | Facebook | Linkedin | Reddit | Ello | Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top