當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。