Java8 中的 Optional 相关用法
基本方法:
ofNullable()
为可能 null 的值创建一个 Optional 实例, 然后可以对该实例遍历/过滤, 判断是否存在,或者为空时执行..ifPresent(...)
如果值存在则执行里面的方法
应用场景:
1> 默认值
传统方式
1 2 3 4 5 | public static String getName(User u) { if (u == null ) return "Unknown" ; return u.name; } |
杜绝使用这种方式(不简洁)
1 2 3 4 5 6 | public static String getName(User u) { Optional<User> user = Optional.ofNullable(u); if (!user.isPresent()) return "Unknown" ; return user.get().name; } |
正确方式(链式调用):
1 2 3 4 5 6 | public static String getName(User u) { return Optional.ofNullable(u) .map(user->user.name) .orElse( "Unknown" ); //.orElseGet(() -> "john"); } |
2>多重非空条件判断
传统方式
1 2 3 4 5 6 7 8 9 10 11 12 | public static String getChampionName(Competition comp) throws IllegalArgumentException { if (comp != null ) { CompResult result = comp.getResult(); if (result != null ) { User champion = result.getChampion(); if (champion != null ) { return champion.getName(); } } } throw new IllegalArgumentException( "The value of param comp isn't available." ); } |
链式调用(map 遍历属性)
1 2 3 4 5 6 7 | public static String getChampionName(Competition comp) throws IllegalArgumentException { return Optional.ofNullable(comp) .map(c->c.getResult()) .map(r->r.getChampion()) .map(u->u.getName()) .orElseThrow(()-> new IllegalArgumentException( "The value of param comp isn't available." )); } |
3> 不为空才操作(单边判断)
1 | string.ifPresent(System.out::println); |
4> 指定条件过滤
1 2 3 4 5 6 | public boolean priceIsInRange2(Modem modem2) { return Optional.ofNullable(modem2) .map(Modem::getPrice) .filter(p -> p >= 10 ) .isPresent(); } |
5. filter 与 findFirst 结合
1 2 3 4 | Optional<String> found = Stream.of(getEmpty(), getHello(), getBye()) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); |
233
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix