This commit is contained in:
Looly 2021-11-16 00:38:10 +08:00
parent e7370ef77c
commit a16b0ed025
2 changed files with 10 additions and 6 deletions

View File

@ -167,12 +167,14 @@ public class Opt<T> {
* }</pre> * }</pre>
* *
* @param action 你想要执行的操作 * @param action 你想要执行的操作
* @return this
* @throws NullPointerException 如果包裹里的值存在但你传入的操作为{@code null}时抛出 * @throws NullPointerException 如果包裹里的值存在但你传入的操作为{@code null}时抛出
*/ */
public void ifPresent(Consumer<? super T> action) { public Opt<T> ifPresent(Consumer<? super T> action) {
if (value != null) { if (isPresent()) {
action.accept(value); action.accept(value);
} }
return this;
} }
/** /**
@ -187,16 +189,16 @@ public class Opt<T> {
* *
* @param action 包裹里的值存在时的操作 * @param action 包裹里的值存在时的操作
* @param emptyAction 包裹里的值不存在时的操作 * @param emptyAction 包裹里的值不存在时的操作
* @return this;
* @throws NullPointerException 如果包裹里的值存在时执行的操作为 {@code null}, 或者包裹里的值不存在时的操作为 {@code null}则抛出{@code NPE} * @throws NullPointerException 如果包裹里的值存在时执行的操作为 {@code null}, 或者包裹里的值不存在时的操作为 {@code null}则抛出{@code NPE}
*/ */
public Opt<T> ifPresentOrElse(Consumer<? super T> action, VoidFunc0 emptyAction) { public Opt<T> ifPresentOrElse(Consumer<? super T> action, VoidFunc0 emptyAction) {
if (isPresent()) { if (isPresent()) {
action.accept(value); action.accept(value);
return ofNullable(value);
} else { } else {
emptyAction.callWithRuntimeException(); emptyAction.callWithRuntimeException();
return empty();
} }
return this;
} }
@ -459,6 +461,7 @@ public class Opt<T> {
/** /**
* 转换为 {@link Optional}对象 * 转换为 {@link Optional}对象
*
* @return {@link Optional}对象 * @return {@link Optional}对象
* @since 5.7.16 * @since 5.7.16
*/ */

View File

@ -149,7 +149,7 @@ public class OptTest {
@Test @Test
public void ofEmptyAbleTest() { public void ofEmptyAbleTest() {
// 以前输入一个CollectionUtil感觉要命类似前缀的类一大堆代码补全形同虚设(在项目中起码要输入完CollectionU才能在第一个调出这个函数) // 以前输入一个CollectionUtil感觉要命类似前缀的类一大堆代码补全形同虚设(在项目中起码要输入完CollectionUtil才能在第一个调出这个函数)
// 关键它还很常用判空和判空集合真的太常用了... // 关键它还很常用判空和判空集合真的太常用了...
List<String> past = Opt.ofNullable(Collections.<String>emptyList()).filter(CollectionUtil::isNotEmpty).orElseGet(() -> Collections.singletonList("hutool")); List<String> past = Opt.ofNullable(Collections.<String>emptyList()).filter(CollectionUtil::isNotEmpty).orElseGet(() -> Collections.singletonList("hutool"));
// 现在一个ofEmptyAble搞定 // 现在一个ofEmptyAble搞定
@ -165,6 +165,7 @@ public class OptTest {
Assert.assertEquals("HUTOOL", hutool); Assert.assertEquals("HUTOOL", hutool);
} }
@SuppressWarnings({"MismatchedQueryAndUpdateOfCollection", "ConstantConditions"})
@Test @Test
public void execTest() { public void execTest() {
// 有一些资深的程序员跟我说你这个lambda双冒号语法糖看不懂... // 有一些资深的程序员跟我说你这个lambda双冒号语法糖看不懂...