Opt get change to getOrNull

This commit is contained in:
Looly 2024-08-20 18:33:07 +08:00
parent 780029c032
commit 9ee9fb8866
13 changed files with 33 additions and 33 deletions

View File

@ -52,8 +52,8 @@ public class WeakCache<K, V> extends TimedCache<K, V>{
final WeakConcurrentMap<Mutable<K>, CacheObj<K, V>> map = (WeakConcurrentMap<Mutable<K>, CacheObj<K, V>>) this.cacheMap; final WeakConcurrentMap<Mutable<K>, CacheObj<K, V>> map = (WeakConcurrentMap<Mutable<K>, CacheObj<K, V>>) this.cacheMap;
// WeakKey回收之后key对应的值已经是null了因此此处的key也为null // WeakKey回收之后key对应的值已经是null了因此此处的key也为null
map.setPurgeListener((key, value)-> listener.onRemove( map.setPurgeListener((key, value)-> listener.onRemove(
Opt.ofNullable(key).map(Ref::get).map(Mutable::get).get(), Opt.ofNullable(key).map(Ref::get).map(Mutable::get).getOrNull(),
Opt.ofNullable(value).map(Ref::get).map(CacheObj::getValue).get())); Opt.ofNullable(value).map(Ref::get).map(CacheObj::getValue).getOrNull()));
return this; return this;
} }

View File

@ -68,7 +68,7 @@ public class CollStreamUtil {
if (CollUtil.isEmpty(collection)) { if (CollUtil.isEmpty(collection)) {
return MapUtil.zero(); return MapUtil.zero();
} }
return toMap(collection, (v) -> Opt.ofNullable(v).map(key).get(), Function.identity(), isParallel); return toMap(collection, (v) -> Opt.ofNullable(v).map(key).getOrNull(), Function.identity(), isParallel);
} }
/** /**

View File

@ -127,7 +127,7 @@ public class CompositeConverter extends RegisterConverter {
// issue#I7WJHHOpt和Optional处理 // issue#I7WJHHOpt和Optional处理
if (value instanceof Opt) { if (value instanceof Opt) {
value = ((Opt<T>) value).get(); value = ((Opt<T>) value).getOrNull();
if (ObjUtil.isNull(value)) { if (ObjUtil.isNull(value)) {
return defaultValue; return defaultValue;
} }

View File

@ -151,16 +151,15 @@ public class Opt<T> {
/** /**
* 返回包裹里的元素取不到则为{@code null}注意此处和{@link java.util.Optional#get()}不同的一点是本方法并不会抛出{@code NoSuchElementException} * 返回包裹里的元素取不到则为{@code null}注意此处和{@link java.util.Optional#get()}不同的一点是本方法并不会抛出{@code NoSuchElementException}
* 如果元素为空则返回{@code null}如果需要一个绝对不能为{@code null}的值则使用{@link #orElseThrow()}
* *
* <p> * <p>
* 如果需要一个绝对不能为 {@code null}的值则使用{@link #orElseThrow()} * 如果元素为空则返回{@code null}如果需要一个绝对不能为 {@code null}的值则使用{@link #orElseThrow()}
* 做此处修改的原因是有时候我们确实需要返回一个null给前端并且这样的时候并不少见 * 做此处修改的原因是有时候我们确实需要返回一个null给前端并且这样的时候并不少见
* 而使用 {@code .orElse(null)}需要写整整12个字符{@code .get()}就只需要6个啦 * 而使用 {@code .orElse(null)}需要写整整12个字符{@code .get()}就只需要6个啦
* *
* @return 包裹里的元素有可能为{@code null} * @return 包裹里的元素有可能为{@code null}
*/ */
public T get() { public T getOrNull() {
return this.value; return this.value;
} }
@ -362,7 +361,8 @@ public class Opt<T> {
*/ */
@SafeVarargs @SafeVarargs
public final Opt<T> ifPresents(final SerConsumer<T>... actions) throws NullPointerException { public final Opt<T> ifPresents(final SerConsumer<T>... actions) throws NullPointerException {
return ifPresent(Stream.of(actions).reduce(SerConsumer::andThen).orElseGet(() -> o -> {})); return ifPresent(Stream.of(actions).reduce(SerConsumer::andThen).orElseGet(() -> o -> {
}));
} }
/** /**

View File

@ -279,7 +279,7 @@ public interface ForestMap<K, V> extends Map<K, TreeEntry<K, V>> {
default V getNodeValue(final K key) { default V getNodeValue(final K key) {
return Opt.ofNullable(get(key)) return Opt.ofNullable(get(key))
.map(TreeEntry::getValue) .map(TreeEntry::getValue)
.get(); .getOrNull();
} }
// ===================== 子节点相关方法 ===================== // ===================== 子节点相关方法 =====================

View File

@ -60,7 +60,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 行是否存在 * @return 行是否存在
*/ */
default boolean containsRow(final R rowKey) { default boolean containsRow(final R rowKey) {
return Opt.ofNullable(rowMap()).map((map) -> map.containsKey(rowKey)).get(); return Opt.ofNullable(rowMap()).map((map) -> map.containsKey(rowKey)).getOrNull();
} }
/** /**
@ -70,7 +70,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 行映射返回的键为列键值为表格的值 * @return 行映射返回的键为列键值为表格的值
*/ */
default Map<C, V> getRow(final R rowKey) { default Map<C, V> getRow(final R rowKey) {
return Opt.ofNullable(rowMap()).map((map) -> map.get(rowKey)).get(); return Opt.ofNullable(rowMap()).map((map) -> map.get(rowKey)).getOrNull();
} }
/** /**
@ -79,7 +79,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 行键 * @return 行键
*/ */
default Set<R> rowKeySet() { default Set<R> rowKeySet() {
return Opt.ofNullable(rowMap()).map(Map::keySet).get(); return Opt.ofNullable(rowMap()).map(Map::keySet).getOrNull();
} }
/** /**
@ -99,7 +99,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 列是否存在 * @return 列是否存在
*/ */
default boolean containsColumn(final C columnKey) { default boolean containsColumn(final C columnKey) {
return Opt.ofNullable(columnMap()).map((map) -> map.containsKey(columnKey)).get(); return Opt.ofNullable(columnMap()).map((map) -> map.containsKey(columnKey)).getOrNull();
} }
/** /**
@ -109,7 +109,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 列映射返回的键为行键值为表格的值 * @return 列映射返回的键为行键值为表格的值
*/ */
default Map<R, V> getColumn(final C columnKey) { default Map<R, V> getColumn(final C columnKey) {
return Opt.ofNullable(columnMap()).map((map) -> map.get(columnKey)).get(); return Opt.ofNullable(columnMap()).map((map) -> map.get(columnKey)).getOrNull();
} }
/** /**
@ -118,7 +118,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 列set * @return 列set
*/ */
default Set<C> columnKeySet() { default Set<C> columnKeySet() {
return Opt.ofNullable(columnMap()).map(Map::keySet).get(); return Opt.ofNullable(columnMap()).map(Map::keySet).getOrNull();
} }
/** /**
@ -157,7 +157,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return * @return
*/ */
default boolean containsValue(final V value){ default boolean containsValue(final V value){
final Collection<Map<C, V>> rows = Opt.ofNullable(rowMap()).map(Map::values).get(); final Collection<Map<C, V>> rows = Opt.ofNullable(rowMap()).map(Map::values).getOrNull();
if(null != rows){ if(null != rows){
for (final Map<C, V> row : rows) { for (final Map<C, V> row : rows) {
if (row.containsValue(value)) { if (row.containsValue(value)) {
@ -176,7 +176,7 @@ public interface Table<R, C, V> extends Iterable<Table.Cell<R, C, V>> {
* @return 如果值不存在返回{@code null} * @return 如果值不存在返回{@code null}
*/ */
default V get(final R rowKey, final C columnKey) { default V get(final R rowKey, final C columnKey) {
return Opt.ofNullable(getRow(rowKey)).map((map) -> map.get(columnKey)).get(); return Opt.ofNullable(getRow(rowKey)).map((map) -> map.get(columnKey)).getOrNull();
} }
/** /**

View File

@ -33,7 +33,7 @@ public class KClassUtil {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static final Class<? extends Annotation> META_DATA_CLASS = private static final Class<? extends Annotation> META_DATA_CLASS =
(Class<? extends Annotation>) Opt.ofTry(() -> Class.forName("kotlin.Metadata")).get(); (Class<? extends Annotation>) Opt.ofTry(() -> Class.forName("kotlin.Metadata")).getOrNull();
/** /**
* 是否提供或处于Kotlin环境中 * 是否提供或处于Kotlin环境中

View File

@ -53,10 +53,10 @@ public class OptTest {
} }
@Test @Test
public void getTest() { public void getOrNullTest() {
// 和原版Optional有区别的是get不会抛出NoSuchElementException // 和原版Optional有区别的是get不会抛出NoSuchElementException
// 如果想使用原版Optional中的get这样获取一个一定不为空的值则应该使用orElseThrow // 如果想使用原版Optional中的get这样获取一个一定不为空的值则应该使用orElseThrow
final Object opt = Opt.ofNullable(null).get(); final Object opt = Opt.ofNullable(null).getOrNull();
Assertions.assertNull(opt); Assertions.assertNull(opt);
} }
@ -77,7 +77,7 @@ public class OptTest {
Assertions.assertEquals("hutool", user.getUsername()); Assertions.assertEquals("hutool", user.getUsername());
// 注意传入的lambda中对包裹内的元素执行赋值操作并不会影响到原来的元素 // 注意传入的lambda中对包裹内的元素执行赋值操作并不会影响到原来的元素
final String name = Opt.ofNullable("hutool").ifPresent(username -> username = "123").ifPresent(username -> username = "456").get(); final String name = Opt.ofNullable("hutool").ifPresent(username -> username = "123").ifPresent(username -> username = "456").getOrNull();
Assertions.assertEquals("hutool", name); Assertions.assertEquals("hutool", name);
} }
@ -99,7 +99,7 @@ public class OptTest {
// 这也是为什么我们需要getter和setter而不直接给bean中的属性赋值中的其中一个原因 // 这也是为什么我们需要getter和setter而不直接给bean中的属性赋值中的其中一个原因
final String name = Opt.ofNullable("hutool").ifPresents( final String name = Opt.ofNullable("hutool").ifPresents(
username -> username = "123", username -> username = "456", username -> username = "123", username -> username = "456",
n -> Assertions.assertEquals("hutool", n)).get(); n -> Assertions.assertEquals("hutool", n)).getOrNull();
Assertions.assertEquals("hutool", name); Assertions.assertEquals("hutool", name);
// 当然以下情况不会抛出NPE但也没什么意义 // 当然以下情况不会抛出NPE但也没什么意义
@ -119,7 +119,7 @@ public class OptTest {
final User user = User.builder().username("hutool").build(); final User user = User.builder().username("hutool").build();
final Opt<User> userOpt = Opt.of(user); final Opt<User> userOpt = Opt.of(user);
// 获取昵称获取不到则获取用户名 // 获取昵称获取不到则获取用户名
final String name = userOpt.map(User::getNickname).or(() -> userOpt.map(User::getUsername)).get(); final String name = userOpt.map(User::getNickname).or(() -> userOpt.map(User::getUsername)).getOrNull();
Assertions.assertEquals("hutool", name); Assertions.assertEquals("hutool", name);
} }

View File

@ -84,7 +84,7 @@ abstract class BaseMutableTest<V, M extends Mutable<V>> {
@Test @Test
void testToOpt() { void testToOpt() {
final Mutable<V> mutableObj = getMutable(getValue1()); final Mutable<V> mutableObj = getMutable(getValue1());
final V value = mutableObj.toOpt().get(); final V value = mutableObj.toOpt().getOrNull();
Assertions.assertEquals(getValue1(), value); Assertions.assertEquals(getValue1(), value);
} }

View File

@ -548,19 +548,19 @@ public class EasyStreamTest {
final Opt<BigDecimal> bigDecimalAvgFullParam = EasyStream.of(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10) final Opt<BigDecimal> bigDecimalAvgFullParam = EasyStream.of(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10)
.map(NumberUtil::toBigDecimal) .map(NumberUtil::toBigDecimal)
.avg(Function.identity(), 2, RoundingMode.HALF_UP); .avg(Function.identity(), 2, RoundingMode.HALF_UP);
Assertions.assertEquals(NumberUtil.toBigDecimal(5.96), bigDecimalAvgFullParam.get()); Assertions.assertEquals(NumberUtil.toBigDecimal(5.96), bigDecimalAvgFullParam.getOrNull());
//测试bigDecimal的avg单参 //测试bigDecimal的avg单参
final Opt<BigDecimal> bigDecimalAvgOneParam = EasyStream.of(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10) final Opt<BigDecimal> bigDecimalAvgOneParam = EasyStream.of(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10)
.map(NumberUtil::toBigDecimal) .map(NumberUtil::toBigDecimal)
.avg(Function.identity()); .avg(Function.identity());
Assertions.assertEquals(NumberUtil.toBigDecimal(5.96), bigDecimalAvgOneParam.get()); Assertions.assertEquals(NumberUtil.toBigDecimal(5.96), bigDecimalAvgOneParam.getOrNull());
//测试bigDecimal的avg双参 //测试bigDecimal的avg双参
final Opt<BigDecimal> bigDecimalAvgTwoParam = EasyStream.of(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10) final Opt<BigDecimal> bigDecimalAvgTwoParam = EasyStream.of(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10)
.map(NumberUtil::toBigDecimal) .map(NumberUtil::toBigDecimal)
.avg(Function.identity(), 2); .avg(Function.identity(), 2);
Assertions.assertEquals(NumberUtil.toBigDecimal(5.96), bigDecimalAvgTwoParam.get()); Assertions.assertEquals(NumberUtil.toBigDecimal(5.96), bigDecimalAvgTwoParam.getOrNull());
//测试bigDecimal的avg 空元素 //测试bigDecimal的avg 空元素
final Opt<BigDecimal> emptyBigDecimalAvg = EasyStream.of(bigDecimalEmptyList) final Opt<BigDecimal> emptyBigDecimalAvg = EasyStream.of(bigDecimalEmptyList)
@ -585,7 +585,7 @@ public class EasyStreamTest {
final BigDecimal sum = EasyStream.of(testList).sum(BigDecimalTest::getCount); final BigDecimal sum = EasyStream.of(testList).sum(BigDecimalTest::getCount);
Assertions.assertEquals(15, sum.intValue()); Assertions.assertEquals(15, sum.intValue());
final BigDecimal avg = EasyStream.of(testList).avg(BigDecimalTest::getCount).get(); final BigDecimal avg = EasyStream.of(testList).avg(BigDecimalTest::getCount).getOrNull();
Assertions.assertEquals(3, avg.intValue()); Assertions.assertEquals(3, avg.intValue());
} }

View File

@ -450,7 +450,7 @@ public class SymmetricCrypto implements SymmetricEncryptor, SymmetricDecryptor,
private SymmetricCrypto initParams(final String algorithm, AlgorithmParameterSpec paramsSpec) { private SymmetricCrypto initParams(final String algorithm, AlgorithmParameterSpec paramsSpec) {
if (null == paramsSpec) { if (null == paramsSpec) {
byte[] iv = Opt.ofNullable(cipher) byte[] iv = Opt.ofNullable(cipher)
.map(JceCipher::getRaw).map(Cipher::getIV).get(); .map(JceCipher::getRaw).map(Cipher::getIV).getOrNull();
// 随机IV // 随机IV
if (StrUtil.startWithIgnoreCase(algorithm, "PBE")) { if (StrUtil.startWithIgnoreCase(algorithm, "PBE")) {

View File

@ -54,7 +54,7 @@ public class StatementUtil {
return StatementBuilder.of() return StatementBuilder.of()
.setConnection(conn) .setConnection(conn)
.setReturnGeneratedKey(returnGeneratedKey) .setReturnGeneratedKey(returnGeneratedKey)
.setSqlFilter(Opt.ofNullable(config).map(DbConfig::getSqlFilters).get()) .setSqlFilter(Opt.ofNullable(config).map(DbConfig::getSqlFilters).getOrNull())
.setSql(sql) .setSql(sql)
.setParams(params) .setParams(params)
.build(); .build();
@ -89,7 +89,7 @@ public class StatementUtil {
return StatementBuilder.of() return StatementBuilder.of()
.setConnection(conn) .setConnection(conn)
.setReturnGeneratedKey(false) .setReturnGeneratedKey(false)
.setSqlFilter(Opt.ofNullable(config).map(DbConfig::getSqlFilters).get()) .setSqlFilter(Opt.ofNullable(config).map(DbConfig::getSqlFilters).getOrNull())
.setSql(sql) .setSql(sql)
.setParamList(StreamUtil.of(paramsBatch).collect(Collectors.toList())) .setParamList(StreamUtil.of(paramsBatch).collect(Collectors.toList()))
.buildForBatch(); .buildForBatch();
@ -109,7 +109,7 @@ public class StatementUtil {
public static CallableStatement prepareCall(final DbConfig config, final Connection conn, final String sql, final Object... params) throws SQLException { public static CallableStatement prepareCall(final DbConfig config, final Connection conn, final String sql, final Object... params) throws SQLException {
return StatementBuilder.of() return StatementBuilder.of()
.setConnection(conn) .setConnection(conn)
.setSqlFilter(Opt.ofNullable(config).map(DbConfig::getSqlFilters).get()) .setSqlFilter(Opt.ofNullable(config).map(DbConfig::getSqlFilters).getOrNull())
.setSql(sql) .setSql(sql)
.setParams(params) .setParams(params)
.buildForCall(); .buildForCall();

View File

@ -145,7 +145,7 @@ public class JSONConverter implements Converter, Serializable {
if (obj instanceof Optional) { if (obj instanceof Optional) {
obj = ((Optional<?>) obj).orElse(null); obj = ((Optional<?>) obj).orElse(null);
} else if (obj instanceof Opt) { } else if (obj instanceof Opt) {
obj = ((Opt<?>) obj).get(); obj = ((Opt<?>) obj).getOrNull();
} }
final JSON json; final JSON json;