Home > Mobile >  How to throw an exception in lambdas operating on methods which returns optional
How to throw an exception in lambdas operating on methods which returns optional

Time:01-06

I wrote some lambda expression which adds some values to the map based on methods which return optionals. I would like to throw some specyfic exception when there is no value under key "A". I'm checking the map using contains But it looks terrible :| I was trying to use orElseThrow but without good results.

Any hints?

Here is some sample code:

package com.aa;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import com.aa.SomeExpection;

public class SomeCLass
{
    Optional<String> methodA()
    {
        return Optional.empty();
    }

    Optional<String> methodB() {
        return Optional.of("example");
    }

    Map methodC() throws SomeExpection {
        Map<String, String> map = new HashMap<>(2);
        methodA().flatMap(s -> {
            map.put("A", s);
            return methodB();
        }).ifPresent(s -> map.put("B", s));


        if (map.containsKey("A")) {
            return map;
        }
        throw new SomeExpection();
    }
}

CodePudding user response:

This is equivalent

Map methodC() throws SomeException {
    Map<String, String> map = new HashMap<>(2);
    map.put("A", methodA().orElseThrow(SomeException::new));
    methodB().ifPresent(s -> map.put("B", s));
    return map;
}

CodePudding user response:

Yes, you can use orElseThrow, like this:

map.put("A", methodA().orElseThrow(() -> new SomeExpection()));
  •  Tags:  
  • Related