9

I was going through a tutorial of Optional class here - https://www.geeksforgeeks.org/java-8-optional-class/ which has the following

String[] words = new String[10];
Optional<String> checkNull = Optional.ofNullable(words[5]);
if (checkNull.isPresent()) {
    String word = words[5].toLowerCase();
    System.out.print(word);
} else{
    System.out.println("word is null");
}

I am trying to make it of less lines using ifPresent check of Optional as

Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase()))

but not able to get the else part further

Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase())).orElse();// doesn't work```

Is there a way to do it?

3
  • 5
    closet you'll come for java-8 would be System.out.println(Optional.ofNullable(words[5]).map(String::toLowerCase).orElse("Not Present")); Commented Jan 7, 2019 at 4:24
  • 1
    Note: I've tagged the question with Java-8 based on the link shared by you, feel free to discard or modify the edit. Commented Jan 7, 2019 at 4:35
  • 1
    have you tried java 9?? BTW good Question :) Commented Jan 7, 2019 at 4:36

3 Answers 3

12

Java-9

Java-9 introduced ifPresentOrElse for something similar in implementation. You could use it as :

Optional.ofNullable(words[5])
        .map(String::toLowerCase) // mapped here itself
        .ifPresentOrElse(System.out::println,
                () -> System.out.println("word is null"));

Java-8

With Java-8, you shall include an intermediate Optional/String and use as :

Optional<String> optional = Optional.ofNullable(words[5])
                                    .map(String::toLowerCase);
System.out.println(optional.isPresent() ? optional.get() : "word is null");

which can also be written as :

String value = Optional.ofNullable(words[5])
                       .map(String::toLowerCase)
                       .orElse("word is null");
System.out.println(value);

or if you don't want to store the value in a variable at all, use:

System.out.println(Optional.ofNullable(words[5])
                           .map(String::toLowerCase)
                           .orElse("word is null"));
Sign up to request clarification or add additional context in comments.

Comments

4

For a bit to be more clear ifPresent will take Consumer as argument and return type is void, so you cannot perform any nested actions on this

public void ifPresent(Consumer<? super T> consumer)

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

Parameters:

consumer - block to be executed if a value is present

Throws:

NullPointerException - if value is present and consumer is null

So instead of ifPreset() use map()

String result =Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null);

print Just to print

System.out.println(Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null));

Comments

3

If you are using java 9, you can use ifPresentOrElse() method::

https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-

Optional.of(words[5]).ifPresentOrElse(
   value -> System.out.println(a.toLowerCase()),
   () -> System.out.println(null)
);

If Java 8 then look this great cheat sheet :

http://www.nurkiewicz.com/2013/08/optional-in-java-8-cheat-sheet.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.