效果好企业营销型网站建设,有没有免费的微网站,做视频比较好的理财网站有哪些,个人养老保险缴费明细一、需求背景 Java8的Optional接口是我们经常使用的一个接口#xff0c;尤其是对对象进行判空的时候#xff0c;需要经常使用到IfPresent()。 但是#xff0c;如果是对List进行判空、循环的话#xff0c;就稍显繁杂了#xff0c;因为几乎每次对List进行操作的时候尤其是对对象进行判空的时候需要经常使用到IfPresent()。 但是如果是对List进行判空、循环的话就稍显繁杂了因为几乎每次对List进行操作的时候都需要先进行IfPresent然后再调用forEach();那么,能否自己写一个方法,将这两结合起来呢?,其实也不难,大致实现如下:
二、具体实现 具体实现步骤、调用方法如下
具体实现
/*** 如果List的IfPresent判断通过,就调用forEach循环* param optionalList 待操作的list* param action forEach操作* param T 消费者对象*/public static T void forEachIfPresent(OptionalListT optionalList, ConsumerT action) {optionalList.ifPresent(items - items.forEach(action));} 调用 public static void main(String[] args) {OptionalListString optionalList Optional.ofNullable(Arrays.asList(A, B, C));ListString list new ArrayList();// 原始的ifPresent、forEach调用System.out.println(-------------------原始调用操作结果-------------------);optionalList.ifPresent(items - {items.forEach(item - {System.out.println(item);list.add(item);});});System.out.println(list);list.clear();// 调用自定义方法实现ifPresent以及forEach循环操作System.out.println(-------------------原始自定义增强方法操作结果-------------------);forEachIfPresent(optionalList,item-{System.out.println(item);list.add(item);});System.out.println(list);}输出结果
-------------------原始调用操作结果-------------------
A
B
C
[A, B, C]
-------------------原始自定义增强方法操作结果-------------------
A
B
C
[A, B, C]可以看到,通过上述组合以后,简化了ifPresent和forEach调用的步骤,并且与原始的调用方法无二.