232. Consuming a present Optional class

Sometimes, all we want is to consume a present Optional class. If Optional is not present then nothing needs to be done. An unskillful solution will rely on the isPresent()-get() pair, as follows:

// Avoid
public void displayStatus() {
Optional<String> status = ...; // this is prone to be empty

if (status.isPresent()) {
System.out.println(status.get());
}
}

A better solution relies on ifPresent(), which takes  Consumer as an argument. This is an alternative to the isPresent()-get() pair when we just need to consume the present value. The code can be rewritten as follows:

// Prefer
public void displayStatus() {
Optional<String> status = ...; // this is prone to be empty

status.ifPresent(System.out::println);
}

But in other cases, if Optional is not present then we want to execute an empty-based action. The solution based on the isPresent()-get() pair is as follows:

// Avoid
public void displayStatus() {
Optional<String> status = ...; // this is prone to be empty

if (status.isPresent()) {
System.out.println(status.get());
} else {
System.out.println("Status not found ...");
}
}

Again, this is not the best choice. Alternatively, we can count on ifPresentOrElse(). This method has been available since JDK 9 and is similar to the ifPresent() method; the only difference is that it covers the else branch as well:

// Prefer
public void displayStatus() {
Optional<String> status = ...; // this is prone to be empty

status.ifPresentOrElse(System.out::println,
() -> System.out.println("Status not found ..."));
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.168.203