Reputation: 177
public class User {
private String id;
private String name;
private List<Types> types;
}
{
private String id;
private String name;
private String linkedTo;
}
private List<Types> getType(List<User> Users) {
return Users
.stream()
.map(User::gettypes)
.flatMap(List::stream)
.collect(Collectors.toList());
}}
public class UserResponse {
private String id;
private String type;
private String name;
private String linkedTo;
}
private List<UserResponse> getUserResponse(UserRequest request) {
List<User> Users = userServiceClient.getById();
List<UserResponse> userResponses = new ArrayList<>();
List<Types> TypesList = getType(Users);
if (!typesList.isEmpty()) {
return typesList.stream()
.map(type -> userResponses.add(new UserResponse( type.getGuid(),type.getName(),type.getName(),type.getLinkedTo())))
.collect(Collectors.toList());
}
return collections.emptylist();
}
Here is the problem, I'm not able to return it as list instead getting a boolean..
Is there any efficient way to do this? The code reviewer doesn't want me to use for each and return the list
Upvotes: 1
Views: 251
Reputation: 31888
A better appraoch would be
private List<UserResponse> getUserResponse(UserRequest request) {
List<User> Users = userServiceClient.getById();
List<Types> TypesList = getType(Users);
return typesList.stream()
.map(type -> new UserResponse(type.getId(), type.getName(), type.getName(), type.getLinkedTo()))
.collect(Collectors.toList());
}
Reason:
If typesList
is empty, this would return empty List
, as Collections.emptyList
in your code.
It map
s to the UserResponse
objects and collects them to return the List<UserResponse>
while using the Stream for it without the explicit instantiation and .add
call.
Upvotes: 2