Skip to content
Advertisement

How to use Map and FlatMap – Java 8 [closed]

How can I use map and flatMap in my example?

I have a class UserProfile that looks like this:

public class UserProfile {
    public final UserId userId;
    public final Optional<AffordabilityCheck> affordabilityCheck;

From UserProfile class I should access AffordabilityCheck class that looks like this:

public class AffordabilityCheck {
    public final RiskGroup riskGroup;
}

From AffordabilityCheck class I should get riskGroup which is an enum and looks like this:

public enum RiskGroup {
    LOW,
    LOW_MEDIUM,
    MEDIUM,
    MEDIUM_HIGH,
    HIGH
}

And return it as String variable

I tried something like this:

String riskGroup = userProfile.flatMap(ac -> ac.getAffordabilityCheck()).map(gr -> gr.getRiskGroup().name());

But I get error:

Required type:
String

Provided:
Optional<java.lang.Object>

How can I do this with map and flatMap?

Advertisement

Answer

Since your code compiles, I would guess that you start with an Optional of UserProfile. Something like this should work:

String riskGroup = userProfile.flatMap(UserProfile::getAffordabilityCheck)
            .map(AffordabilityCheck::getRiskGroup)
            .map(Enum::name)
            .orElse("");

The reason you get this error is that you did not “unpack” the value froma an Optional, and tried to save the riskGroup variable as an Optional of String. You should check the orElse, orElseGet, get and getOrElseThrow methods. Please keep in mind that using Optional#get may end up throwing an NoSuchElementException if the Optional is empty…

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement