In this tutorial, I will show you how you are going to collect objects using Java 8 stream API and map to another custom objects using Java 8 stream API using 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.

Step 1. Create below entity classes. Ideally, entity classes should be mapped to database tables.

package com.roytuts.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;
	}

	public int getId() {
		return id;
	}

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

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

}
package com.roytuts.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;
	}

	public String getGrpName() {
		return grpName;
	}

	public void setGrpName(String grpName) {
		this.grpName = grpName;
	}

	public List<PersonEntity> getPersons() {
		return persons;
	}

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

}

Step 2. Create DTO objects. So we will basically map entity objects to DTO objects using Java 8 Lambda Expression.

package com.roytuts.java8.stream;

public class PersonDto {

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

	public int getId() {
		return id;
	}

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

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

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

}
package com.roytuts.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 + "]";
	}

}

Step 3. Now create below main class that will be used to test the example using dummy values.

package com.roytuts.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=[]]

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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