Optional как выполнить метод map
Перейти к содержимому

Optional как выполнить метод map

  • автор:

# Optional

Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence of the contained value are provided, such as orElse()

(opens new window) , which returns a default value if value not present, and ifPresent() which executes a block of code if the value is present.

(opens new window) method of Optional to work with values that might be null without doing explicit null checks:

(opens new window) operations are evaluated immediately, unlike their Stream counterparts which are only evaluated upon a terminal operation.)

(opens new window) returns an empty optional when its mapping function returns null, you can chain several map() operations as a form of null-safe dereferencing. This is also known as Null-safe chaining.

Consider the following example:

Any of getBar , getBaz , and toString can potentially throw a NullPointerException .

Here is an alternative way to get the value from toString() using Optional :

This will return an empty string if any of the mapping functions returned null.

Below is an another example, but slightly different. It will print the value only if none of the mapping functions returned null.

# Return default value if Optional is empty

(opens new window) since that may throw NoSuchElementException . The Optional.orElse(T)

(opens new window) methods provide a way to supply a default value in case the Optional is empty.

The crucial difference between the orElse and orElseGet is that the latter is only evaluated when the Optional is empty while the argument supplied to the former one is evaluated even if the Optional is not empty. The orElse should therefore only be used for constants and never for supplying value based on any sort of computation.

# Throw an exception, if there is no value

(opens new window) method of Optional to get the contained value or throw an exception, if it hasn’t been set. This is similar to calling get() , except that it allows for arbitrary exception types. The method takes a supplier that must return the exception to be thrown.

In the first example, the method simply returns the contained value:

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

In the second example, the method throws an exception because a value hasn’t been set:

You can also use the lambda syntax if throwing an exception with message is needed:

# Lazily provide a default value using a Supplier

The normal orElse

(opens new window) method takes an Object , so you might wonder why there is an option to provide a Supplier here (the orElseGet method).

It would still call getValueThatIsHardToCalculate() even though it’s result is not used as the optional is not empty.

To avoid this penalty you supply a supplier:

This way getValueThatIsHardToCalculate() will only be called if the Optional is empty.

# Filter

(opens new window) is used to indicate that you would like the value only if it matches your predicate.

Java 8 Optional

Optional — новый класс в пакете java.util, является контейнером (оберткой) для значений которая также может безопасно содержать null.

Благодаря опциональным типам можно забыть про проверки на null и NullPointerException.

2. Optional basics

Для создания Optional используются методы:

Optional.of

В метод Optional.of нельзя передавать null, если конечно мы не хотим получить NullPointerException

— Optional.ofNullable

А вот в метод Optional.ofNullable передавать null можно безопасно

Optional.empty для создания пустого Optional

Для получения значения из Optional используется метод Optional.get, но он является небезопасным и может бросить NoSuchElementException

3. Optional isPresent, ifPresent

3.1 Optional isPresent

Метод Optional.isPresent возвращает true, если значение в нем присутствует, иначе возвращает false

Метод Optional.get лучше использовать в паре с Optional.isPresent чтобы предотвратить исключения

3.2 Optional ifPresent

Метод Optional.ifPresent выполняет переданное действие, если значение в Optional присутствует, иначе игнорирует его. Метод принимает лямбда-выражение известное как потребитель (Consumer).

4. Optional orElse

4.1 Optional orElse

Метод Optional.orElse возвращает переданное значение, если Optional пустой

4.2 Optional orElseGet

Метод Optional.orElseGet возвращает переданное значение из лямда-выражение , если Optional пустой

4.3 Optional orElseThrow

Метод Optional.orElseThrow бросает переданное исключение , если Optional пустой

5. Optional map, flatMap

5.1 Optional map

Метод Optional.map служит для преобразования значения внутри Optional. Если Optional пустой преобразование не будет происходить

5.2 Optional flatMap

Метод Optional.flatMap преобразовывает значение внутри Optional, но при этом не оборачивает их

В Java 8 есть еще множество полезных нововведений, которые можно найти тут

Надеемся — наша статья была Вам полезна. Есть возможность записаться на наши курсы по Java в Киеве. Детальную информацию смотрите у нас на сайте.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *