Java 8 Optional instead of if

I have a problem with an option and I donโ€™t know how to handle it.

public void check(String name) {
   if (name != null)
      doSomething(name);
   else 
      doMore();
} 

How to change this if optional?

+4
source share
4 answers

There is a very neat method for this, but is present in jdk-9 ...

public void check(String name){
     Optional.ofNullable(name)
            .ifPresentOrElse(YourClass::doSomething, YourClass::doMore);
} 

Assuming that doSomethingthey doMoreare static methods ... If you do not use an instance, for example, this::doSomethingorthis::doMore

+13
source

Although there is a way to create the same code with Optional(for example, see Eugeneโ€™s answer), you should not use Optional(imho) here.

Optional , , , / Optional .
Optional . "", , , , , . Optional - , , , , . , , , -, - , , , , , , .


: , .

+6

. , java 8, , if, "" .

,

public void check(String name) {
    Optional<String> nameOpt = Optional.ofNullable(name);
    nameOpt.ifPresent(n -> doSomething(n));
    if (!nameOpt.isPresent()) {
        doMore();
    }
}

. , (, , ): . .

+3

if, Java 8 Optional.map() Optional.orElseGet(). :

import java.util.Optional;
import java.util.function.Consumer;

final class OptionalTestMain {

    public static void main(String[] args) {
        check("test", str -> {
            System.out.println("Yay, string is not null!");
            System.out.println("It's: " + str);
        }, () -> {
            System.out.println("Crap, string is a null...");
            System.out.println("There is nothing for me to do.");
        });

        check(null, str -> {
            System.out.println("Yay, string is not null!");
            System.out.println("It's: " + str);
        }, () -> {
            System.out.println("Crap, string is a null...");
            System.out.println("There is nothing for me to do.");
        });
    }

    static void check(String str, Consumer<String> ifPresent, Runnable ifNotPresent) {
        Optional.ofNullable(str)
                .map(s -> { ifPresent.accept(s); return s; })
                .orElseGet(() -> { ifNotPresent.run(); return null; });
    }
}

:

Yay, string is not null!
It's: test
Crap, string is a null...
There is nothing for me to do.

check 3 :

  • a String (maybe null)
  • a Consumerlambda expression that does something with this value and does not change the input value .
  • a Runnablelambda without parameters to do something when the input Stringis equal null.

Of course, you can easily change the following method, and then use the full potential of the class Optional, for example:

static String checkAndReturn(String str, Function<String, String> ifPresent, Supplier<String> ifNotPresent) {
    return Optional.ofNullable(str)
            .map(ifPresent)
            .orElseGet(ifNotPresent);
}

Then:

System.out.println(checkAndReturn("test", String::toUpperCase, () -> "no value"));
System.out.println(checkAndReturn(null, String::toUpperCase, () -> "no value"));

will produce the following result:

TEST
no value

Hope this helps.

+2
source

Source: https://habr.com/ru/post/1682492/


All Articles