Does the call contain a list for an optional value in Java?

In Java 8,

I currently have a lambda that looks like this:

.createSomething((acceptableStates, someProxy) -> (userId) ->   
    acceptableStates.contains(someProxy.getSomeAttributeId(userId)))

However, we changed someProxy.getSomeAttributeId to return Optional<String>instead of a string.

What is the cleanest / most acceptable way to check if it acceptableStatescontains a value someProxy.getSomeAttributeId(userId)if the returned attribute is not empty?

(Note: acceptableStatesis still a list of strings, not Optional<String>)

+4
source share
3 answers
.... userId -> someProxy.getSomeAttributeId(userId)
                        .map(acceptableStates::contains)
                        .orElse(Boolean.FALSE);
+7
source

, . : Java 8 .ifPresent if-not-Present?

, , getSomeAttributeId .

.createSomething((acceptableIds, someProxy) -> (userId) ->
    {
       Optional<String> attrId = someProxy.getSomeAttributeId(userId);
       return attrId.isPresent() ? acceptableStates.contains(attrId.get()) : false;
    })
+2

, :

Optional<SomeAttributeId> optional = someProxy.getSomeAttributeId(userId);

return optional.isPresent() && acceptableStates.contains(optional.get‌​());

(1), someProxy.getSomeAttributeId(userId) :

acceptableStates.contains(someProxy.getSomeAttributeId(userId).orElseThrow(() -> new Exception()))

, (2), :

acceptableStates.contains(someProxy.getSomeAttributeId(userId).orElse(DEFAUT_VALUE))

:

Java 8, , , . Java-, (1.1), , , . ( ) (1.2).

, "-" / (2).

n- , n > 2 (3).


, , @Eugene .

+2

Source: https://habr.com/ru/post/1682342/


All Articles