I am retrieving data from rest API with a object and want copy that to another Response java object.
Currently I have implemented below with normal java
public OrganizationalUnitTeamsList getTeamsDetails() {
List<OrganizationalUnit> organizationalUnitList = organizationalUnitConnector.getOrganizationalUnit();
OrganizationalUnitTeamsList teamsListResponse = new OrganizationalUnitTeamsList();
List<TeamDetails> availableTeamList = new ArrayList<>();
for (OrganizationalUnit organizationalUnit : organizationalUnitList) {
TeamDetails teams = new TeamDetails();
teams.setHierarchyLevel(organizationalUnit.getHierarchyLevel());
teams.setLocationName(organizationalUnit.getLocationName());
teams.setName(organizationalUnit.getName());
teams.setShortName(organizationalUnit.getShortName());
availableTeamList.add(teams);
}
teamsListResponse.setTeams(availableTeamList);
return teamsListResponse;
}
I want above code to be converted in JAVA 8 way.
Can some suggest me more efficient and code concise way to achieve above logic?
Thank you in advance.
You can do like this,
List<TeamDetails> availableTeamList = organizationalUnitList.stream()
.map(this::convertToTeam)
.collect(collectors.toList());
Then define method convertToTeam
and put the logic of creating new team and populate values there,
private TeamDetails convertToTeam(OrganizationalUnit unit){
TeamDetails team = new teamDetails();
// Setters()
return team;
}
It will do exactly same thing,but it looks bit cleaner and also depending on what your class is doing you could choose to move the method convertToTeam
to its own class to seperate out the concern.
You should consider renaming this class OrganizationalUnitTeamsList
to something like TeamsResponse
it's a unconventional and confusing name for a Class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.