lundi 29 octobre 2018

Conditional initialization in most efficient and readable way

What will be the most efficient way to initialize a Collection (in this example a Map) conditionally? Do you prefer one solution over the other in terms of best practices?

I came with three solutions and I'd like to ask you for your feedback or opinions.

First:

Map<String, User> userMap;
if (isNotEmpty(userIdList)) {
  userService
      .getUsers(userIdList)
      .stream()
      .collect(Collectors.toMap(UserDto::getUserName, Function.identity()));
} else {
  userMap = new HashMap<>();
}

Second:

Map<String, User> userMap = new HashMap<>();
if (isNotEmpty(userIdList)) {
  userService
      .getUsers(userIdList)
      .stream()
      .collect(Collectors.toMap(UserDto::getUserName, Function.identity()));
}

Third:

Map<String, User> userMap = isNotEmpty(userIdList) ?
    userService
    .getUsers(userIdList)
    .stream()
    .collect(Collectors.toMap(UserDto::getUserName, Function.identity()))
    : new HashMap<>();

Thanks for answers.

Aucun commentaire:

Enregistrer un commentaire