Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Lambda of Lambda, if/Else From an Optional

DZone's Guide to

Lambda of Lambda, if/Else From an Optional

Here's a neat workaround for a few JDK 8 Optional interface limitations.

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

So I got frustrated with two limitations of the Optional interface in JDK 8. The first problem is that there is no obvious way to perform an else operation in a block as there is only a isPresent method unless you are using an old school if statement. The second problem is, of course, the old chestnut that even if you could do that the methods would not be able to throw a checked exception. (Yes you can wrap with a RuntimeException but it is not the prettiest).

The workaround I found was to use the map function as the success case and the orElseGet to return the failure case. In both branches, the code returns an instance of ThrowingRunnable by having a lambda return a lambda. The run() is then called at the end and it can throw any exception it wants to.

@FunctionalInterface  
public interface ThrowingRunnable<E extends Throwable>  {  

    public void run() throws E;  
}  



Optional<Credential> credential = ....  

credential.<ThrowingRunnable<IOException>>map(auth -> () -> {  
                PasswordWrapper pw = auth.getToken();  
                ... // something that might throw an IOException  
            }).orElseGet(() -> () -> {  
                        response.setStatus(401);  
                        LOGGER.log(Level.INFO, "credential is not found");  
                    }  
            ).run();  

This is possibly excessive for this particular use case, but I can see this technique being useful elsewhere and it is worth knowing what it looks like so it is not a surprise in others code.

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

Topics:
jdk 8 ,optional ,java ,lambda

Published at DZone with permission of Gerard Davison, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}