我有一个
User
列表,我想将其转换为一个 Id
和 User
的 Map。但是,该列表可能为空,因此如果我使用 Stream 进行转换,它会抛出异常。public Map<Long, User> getUserMap() {
List<User> users = getUserList(); //the method getUserList() can
// return null and this method can not be further changed
return users.stream()
.collect(Collectors.toMap(User::getId, user - > user)));
//throwing nullPointerException when users is null
}
我打算将空Map的返回类型更改为Optional类型。在下面的代码中,如果我已经使用了Optional类型,那么整个操作是否可以像Stream操作那样链接起来,而不是使用if else null检查。这种做法可行吗?
public Optional<Map<Long, User>> getUserMap() {
List<User> users = getUserList(); //the method getUserList() can return null
if (users == null) {
return Optional.empty();
} else {
return Optional.of(users.stream()
.collect(Collectors.toMap(User::getId, user - > user)));
}
}
//not working
public Optional<Map<Long, User>> getUserMap() {
List<User> users = getUserList(); //the method getUserList() can return null
return Optional.ofNullable(users)
.stream()
.collect(Collectors.toMap(User::getId, user -> user));
}
Optional.ofNullable(users).map(list -> list.stream().collect(Collectors.toMap(User::getId, user -> user)))
(或者是用Function.identity()
替代user -> user
) 。 - Thomas