java 8 Optional类

来源:互联网 发布:java获取当前编码格式 编辑:程序博客网 时间:2024/06/18 10:21

在 java.util包中有个类Optional,它是java8的时候才引入的.里面有一些比较重要的方法,总结如下:

A container object which may or may not contain a non-null value,namely,或者包含一个非空的值或者不含一个非空的值得一个容器对象.


1,static <T> Optional<T> empty()  //Returns an empty Optional instance.


2,boolean equals(Object obj) //Indicates whether some other object is "equal to" this Optional.


3,T get() //If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.


4,int hashCode()  //Returns the hash code value of the present value, if any, or 0 (zero) if no value is present.


5,void ifPresent(Consumer<? super T> consumer) //Have the specified consumer accept the value if a value is present, otherwise do nothing.


6,boolean isPresent() //Return true if there is a value present, otherwise false.


7,static <T> Optional<T> of(T value) //Return an Optional with the specified present value.


8,T orElse(T other)  //Return the value if present, otherwise return other.


9,T orElseGet(Supplier<? extends T> other) //Return the value if present, otherwise invoke other and return the result of that invocation.


10,T orElseThrow(Supplier<? extends X> exceptionSupplier)


//Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.


11,String toString() //Returns a non-empty string representation of this Optional suitable for debugging.

原创粉丝点击