Home > Blockchain >  Lambda functions with Optional instead of nested if else
Lambda functions with Optional instead of nested if else

Time:09-22

Optional<String> myData;
Set<String> mySet;
if(myData.isPresent()) {
    if(myData.get().contains(“testValue”)) {
        mySet.add(“somedata”);
    }
}
if(!myData.isPresent()) {
    mySet.add(“someotherdata”);
}

I have a scenario like this. Where I have nested if-else block and I need to convert that into Java8 map using lambda functions. How can I do that?

CodePudding user response:

You could rework your Optional use (this only apply to your code, as originally presented [in case you edit it]):

Optional<String> myData = ...;
mySet.add(myData.filter(value -> value.contains("testValue"))
                .map(ignored -> "somedata")
                .orElse("someotherdata"))

You filter on the value, then map it to somedata or else to someotherdata.

If you are using Java 11, you should use:

myData.filter(value -> value.contains("testValue"))
      .ifPresentOrElse(ignored -> mySet.add("somedata"),
                       () -> mySet.add("someotherdata"));

It is up to you to decide which is better (the first avoid doing mySet.add twice in two part).

CodePudding user response:

The following should work:

Set<String> mySet = myData.stream().map(data -> {
    if(data.contains("testValue")) return "somedata";
    else return "someotherdata";
}).collect(Collectors.toSet());

CodePudding user response:

This will reproduce your earlier results but has been slightly altered. I believe that a stream solution is not necessary nor desirable. The following will:

  • result in an empty set if data is present but not testValue
  • result in the set containing someotherdata if the data is not present
  • result in the set containing somedata if the data is present and matches testValue
String result = myData.isPresent() ?
        (myData.get().contains("testValue") ? "somedata" : "") :
        "someotherdata";

if (!result.isBlank()) {
    mySet.add(result);
}

CodePudding user response:

    Consumer<Set<String>> addSomeOtherdata = s -> s.add("someotherdata");
    Consumer<Set<String>> addSomedata = s -> s.add("somedata");

    Predicate<Optional<String>> isPresent = Optional::isPresent;
    Predicate<Optional<String>> containsTestValue = o -> o.get().contains("testValue");

    Consumer<Optional<String>> mainConsumer = (o -> {
        if (isPresent.and(containsTestValue).test(o)) {
            addSomedata.accept(mySet);
        }
        if (isPresent.negate().test(o)) {
            addSomeOtherdata.accept(mySet);
        }
    });
    mainConsumer.accept(myData);
  • Related