The map method in the java.util.Optional class is a powerful tool for transforming the value contained within an Optional instance if it is present. It is commonly used for operations on potentially nullable values without the need for explicit null checks. Here's a detailed look at how Optional.map works:
Method Signature
public <U> Optional<U> map(Function<? super T, ? extends U> mapper)
Description
- Type Parameters:
<U>- The type of the value returned from the mapping function.
- Parameters:
mapper- A function to apply to the value, if present.
- Returns:
- An
Optionaldescribing the result of applying a mapping function to the value of thisOptional, if a value is present, otherwise an emptyOptional.
- An
Usage
- Input: An
Optionalcontaining a value (or empty). - Process: Apply the provided mapping function to the contained value if present.
- Output: A new
Optionalcontaining the result of the mapping function, or an emptyOptionalif the originalOptionalwas empty.
Example Usage
Basic Example
Optional<String> name = Optional.of("Alice");
Optional<Integer> nameLength = name.map(String::length);
System.out.println(nameLength); // Output: Optional[5]
In this example, map applies the String::length method to the value inside the Optional if it is present, transforming it from Optional<String> to Optional<Integer>.
Handling Empty Optionals
Optional<String> emptyName = Optional.empty();
Optional<Integer> emptyNameLength = emptyName.map(String::length);
System.out.println(emptyNameLength); // Output: Optional.empty
Practical Example
Consider a more practical scenario where you want to extract and transform a value from an Optional object inside a stream of data:
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
List<Optional<String>> names = List.of(Optional.of("Alice"), Optional.empty(), Optional.of("Bob"));
names.stream()
.map(opt -> opt.map(String::toUpperCase))
.forEach(System.out::println);
}
}
554

被折叠的 条评论
为什么被折叠?



