Optional编程实例
@Test public void optionalTest() throws NoSuchMethodException { String firstValue = null; Optional<String> key = Optional.ofNullable(firstValue); String defaultValue = key.orElse("apple"); if (!key.isPresent()) { System.out.println(defaultValue + "001"); } System.out.println(defaultValue); }
结果是
apple001
apple
学习新的写法,新的api
=======================2021-11-12 20:29 =========================
public static class Apple { int size; int price; Color color; public Apple(int size , int price, Color color) { this.size = size; this.price = price; this.color = color; } public void setSize(int size) { this.size = size; } public Color getColor() { return this.color; } }
public static class Color { public Color(int color, Cat cat) { this.color = color; this.cat = cat; } int color; Cat cat; public Cat getCat() { return this.cat; } }
public static class Cat { int age; }
三个class层层嵌套
Apple e = new Apple(1, 1, new Color(1,null)); //Apple e = new Apple(1, 1, null); Cat color = Optional.ofNullable(e).map(u -> u.getColor()).map(c -> c.getCat()).orElse(new Cat());
map方法返回值还是Optional,调用orElse进行取值