首页

Optional用法ifPresent、orElse、orElseThrow代码示例

标签:ifPresent,orElse,orElseThrow     发布时间:2022-11-21   

java.util.Optional的Optional.ofNullable的ifPresent用法、orElse用法、orElseThrow用法    

import java.util.Optional;@b@@b@public class NullableTest {@b@@b@    public static void main(String[] args) {@b@@b@        //1.ifPresent用法@b@        User user=new User();@b@        //新写法:如果optional不为空,则n1赋值111 (n1代表)@b@        user.setUserName("1");@b@        Optional.ofNullable(user.getUserName()).ifPresent(n1->{user.setUserName("111");});@b@        System.out.println("ifPresent:"+user.getUserName());@b@        //赋值null,不走ifPresent赋值逻辑,输出null@b@        user.setUserName(null);@b@        Optional.ofNullable(user.getUserName()).ifPresent(n1->{user.setUserName("aaa");});@b@        System.out.println("ifPresent2:"+user.getUserName());@b@@b@        String  str="bbb";@b@        Optional.ofNullable(str).ifPresent(n->{user.setUserName(n);});@b@        System.out.println("ifPresent3:"+user.getUserName());@b@@b@        //2.orElse用法,str为null则输出222@b@        System.out.println("orElse:"+Optional.ofNullable(str).orElse("222"));@b@@b@@b@        //3.orElseThrow用法,如为null则抛出异常@b@        user.setUserName(null);@b@        Optional.ofNullable(user.getUserName()).orElseThrow(() -> new RuntimeException("用户名不能为空"));@b@@b@    }@b@@b@}

控制台运行结果

ifPresent:111@b@ifPresent2:null@b@ifPresent3:bbb@b@@b@orElse:bbb@b@@b@Exception in thread "main" java.lang.RuntimeException: 用户名不能为空@b@	at com.xwood.demo.optional.NullableTest.lambda$main$3(NullableTest.java:30)@b@	at java.util.Optional.orElseThrow(Optional.java:290)@b@	at com.xwood.demo.optional.NullableTest.main(NullableTest.java:30)
  • ◆ 相关内容
<<推荐下载>>
  •    更多推荐>>
  •