diff --git a/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java b/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java index 9d12052de..6f95a8c7a 100644 --- a/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java +++ b/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java @@ -167,12 +167,14 @@ public class Opt { * } * * @param action 你想要执行的操作 + * @return this * @throws NullPointerException 如果包裹里的值存在,但你传入的操作为{@code null}时抛出 */ - public void ifPresent(Consumer action) { - if (value != null) { + public Opt ifPresent(Consumer action) { + if (isPresent()) { action.accept(value); } + return this; } /** @@ -187,16 +189,16 @@ public class Opt { * * @param action 包裹里的值存在时的操作 * @param emptyAction 包裹里的值不存在时的操作 + * @return this; * @throws NullPointerException 如果包裹里的值存在时,执行的操作为 {@code null}, 或者包裹里的值不存在时的操作为 {@code null},则抛出{@code NPE} */ public Opt ifPresentOrElse(Consumer action, VoidFunc0 emptyAction) { if (isPresent()) { action.accept(value); - return ofNullable(value); } else { emptyAction.callWithRuntimeException(); - return empty(); } + return this; } @@ -459,10 +461,11 @@ public class Opt { /** * 转换为 {@link Optional}对象 + * * @return {@link Optional}对象 * @since 5.7.16 */ - public Optional toOptional(){ + public Optional toOptional() { return Optional.ofNullable(this.value); } diff --git a/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java b/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java index 5409afbb2..013e7897d 100644 --- a/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java @@ -149,7 +149,7 @@ public class OptTest { @Test public void ofEmptyAbleTest() { - // 以前,输入一个CollectionUtil感觉要命,类似前缀的类一大堆,代码补全形同虚设(在项目中起码要输入完CollectionU才能在第一个调出这个函数) + // 以前,输入一个CollectionUtil感觉要命,类似前缀的类一大堆,代码补全形同虚设(在项目中起码要输入完CollectionUtil才能在第一个调出这个函数) // 关键它还很常用,判空和判空集合真的太常用了... List past = Opt.ofNullable(Collections.emptyList()).filter(CollectionUtil::isNotEmpty).orElseGet(() -> Collections.singletonList("hutool")); // 现在,一个ofEmptyAble搞定 @@ -165,6 +165,7 @@ public class OptTest { Assert.assertEquals("HUTOOL", hutool); } + @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection", "ConstantConditions"}) @Test public void execTest() { // 有一些资深的程序员跟我说你这个lambda,双冒号语法糖看不懂...