if-else
1234567891011
User user = ...if (user != null) { String userName = user.getUserName(); if (userName != null) { return userName.toUpperCase(); } else { return null; }} else { return null;}
上面的代码可以简化成:
123456
User user = ...Optional<User> userOpt = Optional.ofNullable(user);return user.map(User::getUserName) .map(String::toUpperCase) .orElse(null);