java.util.Optional#map

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 Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise an empty Optional.

Usage

  • Input: An Optional containing a value (or empty).
  • Process: Apply the provided mapping function to the contained value if present.
  • Output: A new Optional containing the result of the mapping function, or an empty Optional if the original Optional was 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);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值