Home> Java> javaTutorial> body text

What is the importance of Optional.or() method in Java 9?

王林
Release: 2023-08-22 15:57:02
forward
993 people have browsed it

Java 9中Optional.or()方法的重要性是什么?

##In Java 9, some static methods have been added to the

Optional class:stream(), or() andifPresentOrElse() . The introduction of theOptional class solves thenull pointer exception problem. The

Optional.or()method returns anOptionaldescribing a value that is returned if present, otherwise an Optional generated by the provided function.

Syntax

public Optional or(Supplier> supplier)
Copy after login

Example

import java.util.Optional; import java.util.function.Supplier; public class OptionalOrTest { public static void main(String args[]) { Optional optional = Optional.of("TutorialsPoint"); Supplier> supplierString = () -> Optional.of("Not Present"); optional = optional.or(supplierString); optional.ifPresent(x -> System.out.println("Value: " + x)); optional = Optional.empty(); optional = optional.or(supplierString); optional.ifPresent(x -> System.out.println("Value: " + x)); } }
Copy after login

Output

Value: TutorialsPoint Value: Not Present
Copy after login

The above is the detailed content of What is the importance of Optional.or() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!