关于java:JAVA基础之Optional小窍门

39次阅读

共计 790 个字符,预计需要花费 2 分钟才能阅读完成。

Optional.ofNullable() 能够传入空值,并返回 Optional,上面咱们看下这个小窍门挺有意思的

public class FilesTest {
    private String testName;
    private String testAge;
    public Optional<String> getTestName() {return Optional.ofNullable(testName);
    }
    public void setTestName(String testName) {this.testName = testName;}
    public String getTestAge() {return testAge;}
    public void setTestAge(String testAge) {this.testAge = testAge;}
    public static void main(String[] args) throws Exception{FilesTest test = new FilesTest();
        test.setTestAge("12");
        test.setTestName("123");
        String nameResult = test.getTestName().map(testName -> "-" + testName)
                .orElse("No testName");
        System.out.println(nameResult);
        test.setTestName(null);
        nameResult = test.getTestName().map(testName -> "-" + testName)
                .orElse("No testName");
        System.out.println(nameResult);
    }
}
// 输入
- 123
No testName

通过一个 orElse 就能够使 null 值输入了一个 No testName,是不是挺有意思。

正文完
 0