Pkumar
Pkumar

Reputation: 177

Returning boolean instead of list

  1. user class with fields id, name and types
public class User {
    private String id;
    private String name;
    private List<Types> types;
}
  1. Types class with fields id, name , linkedTo
{
    private String id;
    private String name;
    private String linkedTo;

}
  1. Implemented a method to get types from user and return it as list
private List<Types> getType(List<User> Users) {
        return Users
                .stream()
                .map(User::gettypes)
                .flatMap(List::stream)
                .collect(Collectors.toList());
    }}
  1. Now, have to map to response body. For that I have response class:
    public class UserResponse {

    private String id;
    private String type;
    private String name;
    private String linkedTo;

}
  1. Have to map the fields from Types to user response to return it as list
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

Answers (1)

Naman
Naman

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 maps 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

Related Questions