String result = Optional.ofNullable(user) .flatMap(User::getAddress) .flatMap(Address::getCountry) .map(Country::getIsocode) .orElse("default"); 结果现在的代码看起来比之前采用条件分支的冗长代码简洁多了。 Java 9 增强 我们介绍了 Java 8 的特性,Java 9 为 Optional 类添加了三个方法:or()、i...
// 使用 orElseThrow(Supplier<? extends X> exceptionSupplier)Optional<String>name=Optional.ofNullable(null);String greeting="Hello, "+name.orElseThrow(()->newNullPointerException("null"));// 抛出 java.lang.NullPointerException: null 异常 map(Function<? super T,? extends U> mapper) 如果Option...
Optional<string> longest = names .filter(name -> name.startsWith("L")) .findFirst(); Optional<string> lNameInCaps = longest.map(String::toUpperCase); 使用Optional<T>的map方法能够返回另外一个Optional,如上面的LnameInCaps,因为传入map()的参数值也许会导致一个空值。 使用orElse() 如果在T可能空...
例如:System.out::println等同于x->System.out.println(x),String::toLowerCase等同于x->x.toLowerCase(),BigDecimal::new等同于x->new BigDecimal(x)。 二、用法示例 为充分体现Optional类的“威力”,首先以组合方式定义Location和Person两个类。 Location类: public class Location { private String country; ...
// 创建一个非空的 Optional 对象 Optional<String> hello = Optional.of("Hello"); Optional.ofNullable(T value) 注意,如果我们使用 Optional.of 方法传入一个 null 值,会抛出 NullPointerException。如果我们不确定一个值是否为空,可以使用 Optional.ofNullable 方法,它会根据值是否为空,返回一个相应的 Option...
String username=user.getUsername(); System.out.println("Username is: " + username);//使用 username} 但是很多时候,我们可能会忘记写 if (user != null) —— 如果在开发阶段就发现那还好,但是如果在开发阶段没有测试到问题,等到上线却出了 NullPointerException ... 画面太美,我不敢继续想下去。
Return the contained value, if present, otherwise throw an exception to be created by the provided supplier. StringtoString() Returns a non-empty string representation of this Optional suitable for debugging. Methods inherited from class java.lang.Object ...
String name="Unknown";if(null!=people){if(null!=people.getName()){name=people.getName();}}returnname; 这样处理,虽然不用担心NullPointerException了,但是过多的判断语句着实让人头皮发麻,代码变得臃肿不堪。如果对象过于复杂,对象里面还有对象等等,你还要继续逐层判断么?
String version = computer?.getSoundcard()?.getUSB()?.getVersion(); In this case, the variableversionwill be assigned to null ifcomputeris null, orgetSoundcard()returns null, orgetUSB()returns null. You don't need to write complex nested conditions to check for null. ...
Java.Util Assembly: Mono.Android.dll A container object which may or may not contain a non-nullvalue. [Android.Runtime.Register("java/util/Optional", ApiSince=24, DoNotGenerateAcw=true)] [Java.Interop.JavaTypeParameters(new System.String[] { "T" })] public sealed class Optional : Java...