/** * Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. * * @param value the possibly-null value to describe * @return an Optional with a present value if the specified value is non-null, otherwise an empty Optional */ public static <T> Optional<T> ofNullable(T value){ if(value == null){ return empty(); } return new Optional<>(value); }
public String toString(){ if(isPresent()){ return "Optional(" + value.toString() + ")"; } return "Optional()"; } }
/** * Returns an Optional with the specified present non-null value. * * @param value the value to be present, which must be non-null * @return an Optional with the value present */ public static <T> Optional<T> of(@NonNull T value){ return new Optional<>(value); }
/** * If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. * * @return the non-null value held by this Optional * @throws NoSuchElementException - if there is no value present */ public T get(){ if (!isPresent()) { throw new NoSuchElementException("Optional is empty"); } return value; }