Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling contains on 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 have changed someProxy.getSomeAttributeId to return an Optional<String> instead of a string.

What's the cleanest / most accepted way to essentially check for if acceptableStates contains the value of someProxy.getSomeAttributeId(userId) if the attribute returned isn't empty?

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

like image 666
CustardBun Avatar asked Dec 11 '22 10:12

CustardBun


2 Answers

.... userId -> someProxy.getSomeAttributeId(userId)
                        .map(acceptableStates::contains)
                        .orElse(Boolean.FALSE);
like image 160
Eugene Avatar answered Jan 12 '23 23:01

Eugene


I strongly recommend writing understandable and clear code like this snippet:

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

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

If there should not be thrown an exception (1) when someProxy.getSomeAttributeId(userId) is an empty optional:

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

Or unless you have the default value (2) to fill up the result with:

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

My point:

Do not pursue Java 8 features which will mess everything up, especially in cases where a simple boolean expression could be used. I had experience refactoring some code toward plain Java statements because new people (1.1) came in a project could not get what the code does. With the time, even I (as a writer) barely can do so (1.2).

Also, with that "lambda chain" style, one slight change could cause rewriting a snippet/method entirely (2).

It is always fun to poke around n-nested lambdas, where n > 2 (3).


Anyway, if you don't share my point, @Eugene proposed a good way to go with.

like image 22
Andrew Tobilko Avatar answered Jan 12 '23 23:01

Andrew Tobilko