📜  Java8 Optional类

📅  最后修改于: 2020-10-13 03:32:42             🧑  作者: Mango

Java可选类

Java在jdk8中引入了新的Optional类。它是一个公共的最终类,用于处理Java应用程序中的NullPointerException。您必须导入java.util包才能使用此类。它提供了用于检查特定变量的值是否存在的方法。

Java可选的类方法

Methods Description
public static Optional empty() It returns an empty Optional object. No value is present for this Optional.
public static Optional of(T value) It returns an Optional with the specified present non-null value.
public static Optional ofNullable(T value) It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
public T get() If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
public boolean isPresent() It returns true if there is a value present, otherwise false.
public void ifPresent(Consumer consumer) If a value is present, invoke the specified consumer with the value, otherwise do nothing.
public Optional filter(Predicate predicate) If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
public Optional map(Function mapper) If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
public Optional flatMap(Function mapper) If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.
public T orElse(T other) It returns the value if present, otherwise returns other.
public T orElseGet(Supplier other) It returns the value if present, otherwise invoke other and return the result of that invocation.
public T orElseThrow(Supplier exceptionSupplier) throws X extends Throwable It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier.
public boolean equals(Object obj) Indicates whether some other object is “equal to” this Optional or not. The other object is considered equal if:
  • It is also an Optional and;
  • Both instances have no value present or;
  • the present values are “equal to” each other via equals().
public int hashCode() It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present.
public String toString() It returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions.

示例:不使用Optional的Java程序

在下面的示例中,我们没有使用Optional类。该程序异常终止并抛出nullPointerException。

public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
}
}

输出:

Exception in thread "main" java.lang.NullPointerException
at lambdaExample.OptionalExample.main(OptionalExample.java:6)

为了避免异常终止,我们使用Optional类。在下面的示例中,我们使用Optional。因此,我们的程序可以执行而不会崩溃。

Java可选示例:如果不存在Value

import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
Optional checkNull = Optional.ofNullable(str[5]);
    if(checkNull.isPresent()){// check for value is present or not
    String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
    }else
    System.out.println("string value is not present");
}
}

输出:

string value is not present

Java可选示例:如果存在值

import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index
Optional checkNull = Optional.ofNullable(str[5]);
    if(checkNull.isPresent()){// It Checks, value is present or not
    String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
    }else
    System.out.println("String value is not present");
}
}

输出:

java optional class example

另一个Java可选示例

import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE";  // Setting value for 5th index
Optional checkNull = Optional.ofNullable(str[5]);
checkNull.ifPresent(System.out::println);// printing value by using method reference
System.out.println(checkNull.get());// printing value by using get method
System.out.println(str[5].toLowerCase());
}
}

输出:

JAVA OPTIONAL CLASS EXAMPLE
JAVA OPTIONAL CLASS EXAMPLE
java optional class example

Java可选方法示例

import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE";  // Setting value for 5th index
// It returns an empty instance of Optional class 
Optional empty = Optional.empty();
System.out.println(empty);
// It returns a non-empty Optional
Optional value = Optional.of(str[5]);
// If value is present, it returns an Optional otherwise returns an empty Optional
System.out.println("Filtered value: "+value.filter((s)->s.equals("Abc")));
System.out.println("Filtered value: "+value.filter((s)->s.equals("JAVA OPTIONAL CLASS EXAMPLE")));
// It returns value of an Optional. if value is not present, it throws an NoSuchElementException  
System.out.println("Getting value: "+value.get());
// It returns hashCode of the value
System.out.println("Getting hashCode: "+value.hashCode());
// It returns true if value is present, otherwise false
System.out.println("Is value present: "+value.isPresent());
// It returns non-empty Optional if value is present, otherwise returns an empty Optional
System.out.println("Nullable Optional: "+Optional.ofNullable(str[5]));
// It returns value if available, otherwise returns specified value,
System.out.println("orElse: "+value.orElse("Value is not present"));
System.out.println("orElse: "+empty.orElse("Value is not present"));
value.ifPresent(System.out::println);// printing value by using method reference
}
}

输出:

Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE]
Getting value: JAVA OPTIONAL CLASS EXAMPLE
Getting hashCode: -619947648
Is value present: true
Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE]
orElse: JAVA OPTIONAL CLASS EXAMPLE
orElse: Value is not present
JAVA OPTIONAL CLASS EXAMPLE