当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java OptionalDouble ifPresent(DoubleConsumer)用法及代码示例


ifPresentOrElse(java.util.function.DoubleConsumer)方法可帮助我们执行此OptionalDouble对象的值的指定DoubleConsumer操作。如果此OptionalDouble中不存在值,则此方法不执行任何操作。

用法:

public void ifPresentOrElse(DoubleConsumer action)

参数:如果存在值,则此方法接受参数操作,该参数操作是在此Optional上要执行的操作。


返回值:此方法不返回任何内容。

异常:如果存在值且给定操作为null,则此方法抛出NullPodoubleerException。

以下示例程序旨在说明ifPresent(DoubleConsumer)方法:

示例1:

// Java program to demonstrate 
// OptionalDouble.ifPresent(DoubleConsumer) method 
  
import java.util.OptionalDouble; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // create a OptionalDouble 
        OptionalDouble opdouble = OptionalDouble.of(0.23425); 
  
        // apply ifPresent(DoubleConsumer) 
        opdouble.ifPresent((value) -> { 
            value = Math.pow(value, 4); 
            System.out.println("Value after modification:=> "
                               + value); 
        }); 
    } 
}

输出:

示例2:

// Java program to demonstrate 
// OptionalDouble.ifPresent(DoubleConsumer) method 
  
import java.util.OptionalDouble; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // create a OptionalDouble 
        OptionalDouble opdouble = OptionalDouble.empty(); 
  
        // apply ifPresent(DoubleConsumer) 
        opdouble.ifPresent((value) -> { 
            System.out.println("Value:=> "
                               + value); 
        }); 
  
        System.out.println("As OptionalDouble is empty value"
                           + " is not modified"); 
    } 
}

输出:

参考文献: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalDouble.html#ifPresent(java.util.function.DoubleConsumer)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 OptionalDouble ifPresent(DoubleConsumer) method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。