From 31987b9b148e0812bb31626c6c057d3807eca0b0 Mon Sep 17 00:00:00 2001 From: minglipro Date: Tue, 20 Oct 2026 20:05:40 +0800 Subject: [PATCH] a --- .../com/mingliqiye/utils/netty/NettyUtils.kt | 4 +- .../com/mingliqiye/utils/path/OsPath.kt | 42 +- .../random/{RandomBytes.kt => Random.kt} | 7 +- .../com/mingliqiye/utils/require/Require.kt | 229 --- .../mingliqiye/utils/require/RequireTrue.kt | 190 +++ .../com/mingliqiye/utils/require/Required.kt | 23 + .../mingliqiye/utils/stream/SuperStream.java | 1236 +++++++++++++++++ .../utils/stream/SuprtStreamUtils.kt | 0 .../com/mingliqiye/utils/system/SystemUtil.kt | 423 ++---- 9 files changed, 1618 insertions(+), 536 deletions(-) rename src/main/kotlin/com/mingliqiye/utils/random/{RandomBytes.kt => Random.kt} (99%) delete mode 100644 src/main/kotlin/com/mingliqiye/utils/require/Require.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/require/Required.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java rename src/main/{java => kotlin}/com/mingliqiye/utils/stream/SuprtStreamUtils.kt (100%) diff --git a/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt b/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt index c2d25ab..8b27c30 100644 --- a/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt +++ b/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile NettyUtils.kt - * LastUpdate 2026-06-27 21:40:00 + * LastUpdate 2026-10-20 20:05:37 * UpdateUser MingLiPro */ @@ -323,7 +323,7 @@ fun ByteBuf.releaseSafely(): Boolean { */ fun ByteBuf.tryRelease(): Boolean { return try { - if (refCnt() > 0) release() else false + refCnt() > 0 && release() } catch (e: Exception) { false } diff --git a/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt b/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt index 4e9dc63..8a731fc 100644 --- a/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt +++ b/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt @@ -1,5 +1,5 @@ /* - * Copyright 2025 mingliqiye + * Copyright 2026 mingliqiye * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile OsPath.kt - * LastUpdate 2025-09-18 09:47:43 + * LastUpdate 2026-10-20 20:05:37 * UpdateUser MingLiPro */ @@ -26,8 +26,7 @@ package com.mingliqiye.utils.path import java.io.File import java.net.URI -import java.nio.file.Path -import java.nio.file.Paths +import java.nio.file.* import java.util.* import java.util.function.Consumer @@ -40,6 +39,41 @@ class OsPath private constructor(private val path: Path) : Path by path { return path.spliterator() } + override fun startsWith(other: String): Boolean { + return path.startsWith(other) + } + + override fun endsWith(other: String): Boolean { + return path.endsWith(other) + } + + override fun resolve(other: String): Path { + return path.resolve(other) + } + + override fun resolveSibling(other: Path): Path { + return path.resolveSibling(other) + } + + override fun resolveSibling(other: String): Path { + return path.resolveSibling(other) + } + + override fun toFile(): File { + return path.toFile() + } + + override fun register( + watcher: WatchService, + vararg events: WatchEvent.Kind<*>, + ): WatchKey { + return path.register(watcher, *events) + } + + override fun iterator(): MutableIterator { + return path.iterator() + } + companion object { @JvmStatic fun of(path: String): OsPath { diff --git a/src/main/kotlin/com/mingliqiye/utils/random/RandomBytes.kt b/src/main/kotlin/com/mingliqiye/utils/random/Random.kt similarity index 99% rename from src/main/kotlin/com/mingliqiye/utils/random/RandomBytes.kt rename to src/main/kotlin/com/mingliqiye/utils/random/Random.kt index 361e119..5462b93 100644 --- a/src/main/kotlin/com/mingliqiye/utils/random/RandomBytes.kt +++ b/src/main/kotlin/com/mingliqiye/utils/random/Random.kt @@ -15,10 +15,11 @@ * * ProjectName mingli-utils * ModuleName mingli-utils.main - * CurrentFile RandomBytes.kt - * LastUpdate 2026-10-11 17:11:11 + * CurrentFile Random.kt + * LastUpdate 2026-10-20 20:05:37 * UpdateUser MingLiPro */ + package com.mingliqiye.utils.random import java.security.SecureRandom @@ -44,7 +45,7 @@ object Random { * 通过lazy委托延迟初始化 */ private val random: Random by lazy { - Random + Random.Default } /** diff --git a/src/main/kotlin/com/mingliqiye/utils/require/Require.kt b/src/main/kotlin/com/mingliqiye/utils/require/Require.kt deleted file mode 100644 index bad6eaa..0000000 --- a/src/main/kotlin/com/mingliqiye/utils/require/Require.kt +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2026 mingliqiye - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ProjectName mingli-utils - * ModuleName mingli-utils.main - * CurrentFile Require.kt - * LastUpdate 2026-02-24 09:03:42 - * UpdateUser MingLiPro - */ - -package com.mingliqiye.utils.require - -import com.mingliqiye.utils.logger.MingLiLoggerFactory -import org.slf4j.Logger -import java.lang.reflect.Constructor -import kotlin.contracts.ExperimentalContracts -import kotlin.contracts.contract -import kotlin.reflect.KClass - -/** - * 条件检查工具对象,提供多种重载的require方法用于参数验证和异常抛出 - * 支持自定义异常类型、延迟消息构造和日志记录功能 - */ -object Require { - @JvmStatic - var logger: Logger? = MingLiLoggerFactory.getLogger() - - @JvmStatic - var isLogError = true - - /** - * 检查条件是否满足,如果不满足则抛出指定类型的异常 - * @param value 要检查的布尔条件 - * @param throwable 异常类型Class对象 - * @param layzMessage 延迟消息构造器 - */ - @JvmStatic - @OptIn(ExperimentalContracts::class) - fun require(value: Boolean, throwable: Class, layzMessage: RequireLayzMessageConstructor) { - contract { - returns() implies value - } - require(value, layzMessage.call(), throwable) - } - - /** - * 检查条件是否满足,如果不满足则抛出指定类型的异常 - * @param value 要检查的布尔条件 - * @param throwable 异常类型KClass对象 - * @param layzMessage 延迟消息构造器 - */ - @JvmStatic - @OptIn(ExperimentalContracts::class) - fun require(value: Boolean, throwable: KClass, layzMessage: RequireLayzMessageConstructor) { - contract { - returns() implies value - } - require(value, throwable.java, layzMessage) - } - - /** - * 检查条件是否满足,如果不满足则抛出延迟构造的异常 - * @param value 要检查的布尔条件 - * @param layzThrowable 延迟异常构造器 - */ - @JvmStatic - @OptIn(ExperimentalContracts::class) - fun require(value: Boolean, layzThrowable: RequireLayzExceptionConstructor) { - contract { - returns() implies value - } - if (!value) throwThrowable(layzThrowable.call()) - } - - /** - * 检查条件是否满足,如果不满足则抛出指定消息和类型的异常 - * @param value 要检查的布尔条件 - * @param message 异常消息 - * @param throwable 异常类型Class对象 - */ - @JvmStatic - @OptIn(ExperimentalContracts::class) - fun require(value: Boolean, message: String, throwable: Class) { - contract { - returns() implies value - } - if (!value) throwThrowable(getExceptionConstructor(throwable).newInstance(message)) - } - - /** - * 检查条件是否满足,如果不满足则抛出指定消息和类型的异常 - * @param value 要检查的布尔条件 - * @param message 异常消息 - * @param throwable 异常类型KClass对象 - */ - @JvmStatic - @OptIn(ExperimentalContracts::class) - fun require(value: Boolean, message: String, throwable: KClass) { - contract { - returns() implies value - } - require(value, message, throwable.java) - } - - /** - * 抛出异常并在启用日志时记录错误信息 - * @param throwable 要抛出的异常对象 - */ - @JvmStatic - fun throwThrowable(throwable: Throwable) { - if (isLogError && logger != null) logger!!.error(throwable.message, throwable) - throw throwable - } - - /** - * 内联函数版本的条件检查,支持泛型异常类型 - * @param T 异常类型 - * @param value 要检查的布尔条件 - * @param message 异常消息 - */ - @OptIn(ExperimentalContracts::class) - @JvmName("__inline_Require") - @JvmStatic - inline fun require(value: Boolean, message: String) { - contract { - returns() implies value - } - require(value, message, T::class.java) - } - - /** - * 内联函数版本的条件检查,支持泛型异常类型和延迟消息构造 - * @param T 异常类型 - * @param value 要检查的布尔条件 - * @param layzMessage 延迟消息构造器 - */ - @OptIn(ExperimentalContracts::class) - @JvmName("__inline_Require") - @JvmStatic - inline fun require(value: Boolean, layzMessage: RequireLayzMessageConstructor) { - contract { - returns() implies value - } - if (!value) throwThrowable(getExceptionConstructor().newInstance(layzMessage.call())) - } - - /** - * 获取指定异常类型的构造函数(内联泛型版本) - * @param T 异常类型 - * @return 异常类型的构造函数 - */ - @JvmName("__inline_GetExceptionConstructor") - @JvmStatic - inline fun getExceptionConstructor(): Constructor = - getExceptionConstructor(T::class.java) - - /** - * 获取指定异常类型的构造函数 - * @param throwable 异常类型Class对象 - * @return 异常类型的构造函数 - */ - @JvmStatic - @JvmName("__GetExceptionConstructor") - fun getExceptionConstructor(throwable: Class): Constructor = - throwable.getConstructor(String::class.java) - - /** - * 获取指定异常类型的构造函数 - * @param throwable 异常类型KClass对象 - * @return 异常类型的构造函数 - */ - @JvmStatic - @JvmName("__GetExceptionConstructor") - fun getExceptionConstructor(throwable: KClass): Constructor = - getExceptionConstructor(throwable.java) - - /** - * 基础条件检查方法,不满足条件时抛出IllegalArgumentException - * @param value 要检查的布尔条件 - */ - @OptIn(ExperimentalContracts::class) - @JvmStatic - fun require(value: Boolean) { - contract { - returns() implies value - } - require(value, "the require conditions are not met.") - } - - /** - * 使用延迟消息构造器进行条件检查,不满足时抛出IllegalArgumentException - * @param value 要检查的布尔条件 - * @param layzMessage 延迟消息构造器 - */ - @OptIn(ExperimentalContracts::class) - @JvmStatic - fun requireLayzMessage(value: Boolean, layzMessage: RequireLayzMessageConstructor) { - contract { - returns() implies value - } - require(value, IllegalArgumentException::class.java, layzMessage) - } - - /** - * 带消息的条件检查方法,不满足条件时抛出IllegalArgumentException - * @param value 要检查的布尔条件 - * @param message 异常消息 - */ - @OptIn(ExperimentalContracts::class) - @JvmStatic - fun require(value: Boolean, message: String) { - contract { - returns() implies value - } - if (!value) throwThrowable(getExceptionConstructor(IllegalArgumentException::class.java).newInstance(message)) - } -} diff --git a/src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt b/src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt new file mode 100644 index 0000000..93d2075 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt @@ -0,0 +1,190 @@ +/* + * Copyright 2026 mingliqiye + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ProjectName mingli-utils + * ModuleName mingli-utils.main + * CurrentFile RequireTrue.kt + * LastUpdate 2026-10-20 20:05:24 + * UpdateUser MingLiPro + */ + +package com.mingliqiye.utils.require + +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.contract + +const val DEFAULT_MESSAGE = "required fail" + +class Required(private val newException: (message: String) -> T) { + + + @OptIn(ExperimentalContracts::class) + fun requireTrue(value: Boolean, message: String) { + contract { + returns() implies value + } + requireTrue(value) { message } + } + + @OptIn(ExperimentalContracts::class) + fun requireTrue(value: Boolean) { + contract { + returns() implies value + } + requireTrue(value) { DEFAULT_MESSAGE } + } + + @OptIn(ExperimentalContracts::class) + fun requireTrue(value: Boolean, lazyMessage: () -> String) { + contract { + returns() implies value + } + if (!value) { + throw newException(lazyMessage()) + } + } + +} + +fun newRequired(): Required { + return newRequired() +} + +fun newRequired(clazz: Class): Required { + return Required { + newException(clazz, it) + } +} + +inline fun newRequired(): Required { + return newRequired(T::class.java) +} + +fun newException(clazz: Class, msg: String): T = try { + val constructor = clazz.getConstructor(String::class.java).also { + check(!java.lang.reflect.Modifier.isAbstract(clazz.modifiers)) { + "${clazz.name} 是抽象类,无法实例化" + } + } + constructor.newInstance(msg) +} catch (e: ReflectiveOperationException) { + throw IllegalStateException("无法实例化 ${clazz.name}", e) +} + +@OptIn(ExperimentalContracts::class) +fun requireTrue(value: Boolean, clazz: Class, lazyMessage: () -> String) { + contract { + returns() implies value + } + if (!value) { + throw newException(clazz, lazyMessage()) + } +} + +@OptIn(ExperimentalContracts::class) +inline fun requireTrue(value: Boolean, noinline lazyMessage: () -> String) { + contract { + returns() implies value + } + requireTrue(value, T::class.java, lazyMessage) +} + +@OptIn(ExperimentalContracts::class) +fun Boolean.requireTrue(clazz: Class, lazyMessage: () -> String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, clazz, lazyMessage) +} + +@OptIn(ExperimentalContracts::class) +fun Boolean.requireTrue(clazz: Class, message: String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, clazz) { + message + } +} + +@OptIn(ExperimentalContracts::class) +fun requireTrue(value: Boolean, clazz: Class, message: String) { + contract { + returns() implies value + } + requireTrue(value, clazz) { message } +} + +@OptIn(ExperimentalContracts::class) +inline fun requireTrue(value: Boolean, message: String) { + contract { + returns() implies value + } + requireTrue(value, T::class.java) { message } +} + + +@OptIn(ExperimentalContracts::class) +inline fun Boolean.requireTrue(noinline lazyMessage: () -> String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, T::class.java, lazyMessage) + +} + +@OptIn(ExperimentalContracts::class) +inline fun Boolean.requireTrue(message: String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, T::class.java, message) + +} + +@OptIn(ExperimentalContracts::class) +fun requireTrue(value: Boolean, clazz: Class) { + contract { + returns() implies value + } + requireTrue(value, clazz) { DEFAULT_MESSAGE } +} + +@OptIn(ExperimentalContracts::class) +inline fun requireTrue(value: Boolean) { + contract { + returns() implies value + } + requireTrue(value, T::class.java) { DEFAULT_MESSAGE } +} + + +@OptIn(ExperimentalContracts::class) +fun Boolean.requireTrue(clazz: Class) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, clazz) { DEFAULT_MESSAGE } + +} + +@OptIn(ExperimentalContracts::class) +inline fun Boolean.requireTrue() { + contract { + returns() implies this@requireTrue + } + requireTrue(this, T::class.java) { DEFAULT_MESSAGE } + +} diff --git a/src/main/kotlin/com/mingliqiye/utils/require/Required.kt b/src/main/kotlin/com/mingliqiye/utils/require/Required.kt new file mode 100644 index 0000000..60d3452 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/require/Required.kt @@ -0,0 +1,23 @@ +/* + * Copyright 2026 mingliqiye + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ProjectName mingli-utils + * ModuleName mingli-utils.main + * CurrentFile Required.kt + * LastUpdate 2026-10-20 19:58:06 + * UpdateUser MingLiPro + */ + +package com.mingliqiye.utils.require diff --git a/src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java b/src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java new file mode 100644 index 0000000..6939bff --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java @@ -0,0 +1,1236 @@ +/* + * Copyright 2026 mingliqiye + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ProjectName mingli-utils + * ModuleName mingli-utils.main + * CurrentFile SuperStream.java + * LastUpdate 2026-10-20 20:05:37 + * UpdateUser MingLiPro + */ + +package com.mingliqiye.utils.stream; + +import com.mingliqiye.utils.collection.Collections; +import com.mingliqiye.utils.functions.P1Function; +import com.mingliqiye.utils.functions.P2Function; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Array; +import java.util.*; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.*; +import java.util.stream.*; + + +/** + * SuperStream是一个增强版的Stream包装器,提供了更多的便捷方法和重载方法来处理各种数据类型的流操作。 + * 它继承了Stream接口并实现了所有Stream的方法,同时添加了一些额外的便利功能。 + */ +public class SuperStream implements Stream { + + private final Stream stream; + + + /** + * 构造一个新的SuperStream实例 + * + * @param stream 被包装的基础Stream对象 + */ + private SuperStream(Stream stream) { + this.stream = stream; + } + + /** + * 创建一个包含指定整数元素的SuperStream + * + * @param args 可变参数的整数值数组 + * @return 包含指定整数的SuperStream实例 + */ + public static SuperStream of(int... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定字节元素的SuperStream + * + * @param args 可变参数的字节数组 + * @return 包含指定字节的SuperStream实例 + */ + public static SuperStream of(byte... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定短整数元素的SuperStream + * + * @param args 可变参数的短整数数组 + * @return 包含指定短整数的SuperStream实例 + */ + public static SuperStream of(short... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定字符元素的SuperStream + * + * @param args 可变参数的字符数组 + * @return 包含指定字符的SuperStream实例 + */ + public static SuperStream of(char... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定长整数元素的SuperStream + * + * @param args 可变参数的长整数数组 + * @return 包含指定长整数的SuperStream实例 + */ + public static SuperStream of(long... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定布尔元素的SuperStream + * + * @param args 可变参数的布尔数组 + * @return 包含指定布尔的SuperStream实例 + */ + public static SuperStream of(boolean... args) { + return of(Collections.newArrayLists(args)); + } + + + /** + * 创建一个包含指定浮点数元素的SuperStream + * + * @param args 可变参数的浮点数数组 + * @return 包含指定浮点数的SuperStream实例 + */ + public static SuperStream of(float... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定双精度浮点数元素的SuperStream + * + * @param args 可变参数的双精度浮点数数组 + * @return 包含指定双精度浮点数的SuperStream实例 + */ + public static SuperStream of(double... args) { + return of(Collections.newArrayLists(args)); + } + + + /** + * 将现有的Stream包装成SuperStream + * + * @param stream 需要包装的Stream对象 + * @param 流中元素的类型 + * @return 包装后的SuperStream实例 + */ + public static SuperStream of(Stream stream) { + return new SuperStream<>(stream); + } + + /** + * 创建一个包含指定数组元素的SuperStream,支持并行处理 + * + * @param ts 元素数组 + * @param parallel 是否使用并行流 + * @param 数组元素的类型 + * @return 包含指定数组元素的SuperStream实例 + */ + public static SuperStream of(T[] ts, boolean parallel) { + return of(Collections.newArrayLists(ts), parallel); + } + + /** + * 创建一个包含指定数组元素的SuperStream(默认串行) + * + * @param ts 元素数组 + * @param 数组元素的类型 + * @return 包含指定数组元素的SuperStream实例 + */ + public static SuperStream of(T[] ts) { + return of(ts, false); + } + + + /** + * 创建一个包含指定集合元素的SuperStream(默认串行) + * + * @param collection 包含元素的集合 + * @param 集合元素的类型 + * @return 包含指定集合元素的SuperStream实例 + */ + public static SuperStream of(Collection collection) { + return of(collection, false); + } + + + /** + * 创建一个包含指定Map键值对Entry的SuperStream(默认串行) + * + * @param map 源Map对象 + * @param Map的键类型 + * @param Map的值类型 + * @return 包含Map Entry的SuperStream实例 + */ + public static SuperStream> of(Map map) { + return of(map.entrySet(), false); + } + + + /** + * 创建一个包含指定Map键值对Entry的SuperStream,支持并行处理 + * + * @param map 源Map对象 + * @param parallel 是否使用并行流 + * @param Map的键类型 + * @param Map的值类型 + * @return 包含Map Entry的SuperStream实例 + */ + public static SuperStream> of(Map map, boolean parallel) { + return SuperStream.of(map.entrySet(), parallel); + } + + + /** + * 创建一个包含指定集合元素的SuperStream,支持并行处理 + * + * @param stream 包含元素的集合 + * @param parallel 是否使用并行流 + * @param 集合元素的类型 + * @return 包含指定集合元素的SuperStream实例 + */ + public static SuperStream of(Collection stream, boolean parallel) { + return parallel ? SuperStream.of(stream.parallelStream()) : SuperStream.of(stream.stream()); + } + + + /** + * 返回一个收集器,该收集器产生一个DoubleSummaryStatistics,描述输入元素的统计信息 + * + * @param mapper 用于将输入元素映射到double值的函数 + * @param 输入元素的类型 + * @return 产生DoubleSummaryStatistics的收集器 + */ + public static Collector summarizingDouble(@NotNull ToDoubleFunction mapper) { + return Collectors.summarizingDouble(mapper); + } + + + /** + * 返回一个收集器,该收集器产生一个LongSummaryStatistics,描述输入元素的统计信息 + * + * @param mapper 用于将输入元素映射到long值的函数 + * @param 输入元素的类型 + * @return 产生LongSummaryStatistics的收集器 + */ + public static Collector summarizingLong(@NotNull ToLongFunction mapper) { + return Collectors.summarizingLong(mapper); + } + + + /** + * 返回一个收集器,该收集器产生一个IntSummaryStatistics,描述输入元素的统计信息 + * + * @param mapper 用于将输入元素映射到int值的函数 + * @param 输入元素的类型 + * @return 产生IntSummaryStatistics的收集器 + */ + public static Collector summarizingInt(@NotNull ToIntFunction mapper) { + return Collectors.summarizingInt(mapper); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到ConcurrentMap中 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param mapSupplier 用于创建新Map的供应函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @param Map的具体类型 + * @return 产生ConcurrentMap的收集器 + */ + public static > Collector toConcurrentMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction, @NotNull Supplier mapSupplier) { + return Collectors.toConcurrentMap(keyMapper, valueMapper, mergeFunction, mapSupplier); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到ConcurrentMap中,使用BinaryOperator处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector> toConcurrentMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction) { + return Collectors.toConcurrentMap(keyMapper, valueMapper, mergeFunction); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到ConcurrentMap中,使用HashMap.merge处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector> toConcurrentMap(@NotNull Function keyMapper, @NotNull Function valueMapper) { + return Collectors.toConcurrentMap(keyMapper, valueMapper); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param mapSupplier 用于创建新Map的供应函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @param Map的具体类型 + * @return 产生Map的收集器 + */ + public static > Collector toMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction, @NotNull Supplier mapSupplier) { + return Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中,使用BinaryOperator处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生Map的收集器 + */ + public static Collector> toMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction) { + return Collectors.toMap(keyMapper, valueMapper, mergeFunction); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中,使用HashMap.merge处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生Map的收集器 + */ + public static Collector> toMap(@NotNull Function keyMapper, @NotNull Function valueMapper) { + return Collectors.toMap(keyMapper, valueMapper); + } + + + /** + * 返回一个收集器,该收集器根据谓词将输入元素分区到Map中 + * + * @param predicate 用于确定元素分区的谓词 + * @param downstream 应用于分区结果的下游收集器 + * @param 输入元素的类型 + * @param 下游收集器的结果类型 + * @param 下游收集器的累加器类型 + * @return 产生分区Map的收集器 + */ + public static Collector> partitioningBy(@NotNull Predicate predicate, @NotNull Collector downstream) { + return Collectors.partitioningBy(predicate, downstream); + } + + + /** + * 返回一个收集器,该收集器根据谓词将输入元素分区到Map中 + * + * @param predicate 用于确定元素分区的谓词 + * @param 输入元素的类型 + * @return 产生分区Map的收集器 + */ + public static Collector>> partitioningBy(@NotNull Predicate predicate) { + return Collectors.partitioningBy(predicate); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到ConcurrentMap中 + * + * @param classifier 用于分类元素的函数 + * @param mapFactory 用于创建Map的工厂函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的结果类型 + * @param 下游收集器的累加器类型 + * @param Map的具体类型 + * @return 产生ConcurrentMap的收集器 + */ + public static > Collector groupingByConcurrent(@NotNull Function classifier, @NotNull Supplier mapFactory, @NotNull Collector downstream) { + return Collectors.groupingByConcurrent(classifier, mapFactory, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到ConcurrentMap中 + * + * @param classifier 用于分类元素的函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector> groupingByConcurrent(@NotNull Function classifier, @NotNull Collector downstream) { + return Collectors.groupingByConcurrent(classifier, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到ConcurrentMap中 + * + * @param classifier 用于分类元素的函数 + * @param 输入元素的类型 + * @param 分类键的类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector>> groupingByConcurrent(@NotNull Function classifier) { + return Collectors.groupingByConcurrent(classifier); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到Map中 + * + * @param classifier 用于分类元素的函数 + * @param mapFactory 用于创建Map的工厂函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的结果类型 + * @param 下游收集器的累加器类型 + * @param Map的具体类型 + * @return 产生Map的收集器 + */ + public static > Collector groupingBy(@NotNull Function classifier, @NotNull Supplier mapFactory, @NotNull Collector downstream) { + return Collectors.groupingBy(classifier, mapFactory, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到Map中 + * + * @param classifier 用于分类元素的函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @return 产生Map的收集器 + */ + public static Collector> groupingBy(@NotNull Function classifier, @NotNull Collector downstream) { + return Collectors.groupingBy(classifier, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到Map中 + * + * @param classifier 用于分类元素的函数 + * @param 输入元素的类型 + * @param 分类键的类型 + * @return 产生Map的收集器 + */ + public static Collector>> groupingBy(@NotNull Function classifier) { + return Collectors.groupingBy(classifier); + } + + + /** + * 返回一个收集器,该收集器执行归约操作 + * + * @param identity 归约操作的初始值 + * @param mapper 用于将输入元素映射到中间值的函数 + * @param op 用于组合中间值的二元操作符 + * @param 输入元素的类型 + * @param 中间值和结果的类型 + * @return 执行归约操作的收集器 + */ + public static Collector reducing(U identity, @NotNull Function mapper, @NotNull BinaryOperator op) { + return Collectors.reducing(identity, mapper, op); + } + + + /** + * 返回一个收集器,该收集器执行归约操作 + * + * @param op 用于组合元素的二元操作符 + * @param 输入元素的类型 + * @return 执行归约操作的收集器 + */ + public static Collector> reducing(@NotNull BinaryOperator op) { + return Collectors.reducing(op); + } + + + /** + * 返回一个收集器,该收集器执行归约操作 + * + * @param identity 归约操作的初始值 + * @param op 用于组合元素的二元操作符 + * @param 输入元素的类型 + * @return 执行归约操作的收集器 + */ + public static Collector reducing(T identity, @NotNull BinaryOperator op) { + return Collectors.reducing(identity, op); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的平均值 + * + * @param mapper 用于将输入元素映射到double值的函数 + * @param 输入元素的类型 + * @return 计算平均值的收集器 + */ + public static Collector averagingDouble(@NotNull ToDoubleFunction mapper) { + return Collectors.averagingDouble(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的平均值 + * + * @param mapper 用于将输入元素映射到long值的函数 + * @param 输入元素的类型 + * @return 计算平均值的收集器 + */ + public static Collector averagingLong(@NotNull ToLongFunction mapper) { + return Collectors.averagingLong(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的平均值 + * + * @param mapper 用于将输入元素映射到int值的函数 + * @param 输入元素的类型 + * @return 计算平均值的收集器 + */ + public static Collector averagingInt(@NotNull ToIntFunction mapper) { + return Collectors.averagingInt(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的总和 + * + * @param mapper 用于将输入元素映射到double值的函数 + * @param 输入元素的类型 + * @return 计算总和的收集器 + */ + public static Collector summingDouble(@NotNull ToDoubleFunction mapper) { + return Collectors.summingDouble(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的总和 + * + * @param mapper 用于将输入元素映射到long值的函数 + * @param 输入元素的类型 + * @return 计算总和的收集器 + */ + public static Collector summingLong(@NotNull ToLongFunction mapper) { + return Collectors.summingLong(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的总和 + * + * @param mapper 用于将输入元素映射到int值的函数 + * @param 输入元素的类型 + * @return 计算总和的收集器 + */ + public static Collector summingInt(@NotNull ToIntFunction mapper) { + return Collectors.summingInt(mapper); + } + + + /** + * 返回一个收集器,该收集器根据比较器找到最大元素 + * + * @param comparator 用于比较元素的比较器 + * @param 输入元素的类型 + * @return 找到最大元素的收集器 + */ + public static Collector> maxBy(@NotNull Comparator comparator) { + return Collectors.maxBy(comparator); + } + + + /** + * 返回一个收集器,该收集器根据比较器找到最小元素 + * + * @param comparator 用于比较元素的比较器 + * @param 输入元素的类型 + * @return 找到最小元素的收集器 + */ + public static Collector> minBy(@NotNull Comparator comparator) { + return Collectors.minBy(comparator); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的数量 + * + * @param 输入元素的类型 + * @return 计算元素数量的收集器 + */ + public static Collector counting() { + return Collectors.counting(); + } + + + /** + * 返回一个收集器,该收集器在应用下游收集器后执行finisher转换 + * + * @param downstream 下游收集器 + * @param finisher 在下游收集器完成后应用的finisher函数 + * @param 输入元素的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @param 最终结果类型 + * @return 执行转换的收集器 + */ + public static Collector collectingAndThen(@NotNull Collector downstream, @NotNull Function finisher) { + return Collectors.collectingAndThen(downstream, finisher); + } + + + /** + * 返回一个收集器,该收集器将输入元素映射后应用下游收集器 + * + * @param mapper 用于映射输入元素的函数 + * @param downstream 应用于映射后元素的下游收集器 + * @param 输入元素的类型 + * @param 映射后元素的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @return 执行映射和收集的收集器 + */ + public static Collector mapping(@NotNull Function mapper, @NotNull Collector downstream) { + return Collectors.mapping(mapper, downstream); + } + + + /** + * 返回一个收集器,该收集器连接输入的字符序列 + * + * @param delimiter 分隔符 + * @param prefix 前缀 + * @param suffix 后缀 + * @return 连接字符序列的收集器 + */ + public static Collector joining(@NotNull CharSequence delimiter, @NotNull CharSequence prefix, @NotNull CharSequence suffix) { + return Collectors.joining(delimiter, prefix, suffix); + } + + + /** + * 返回一个收集器,该收集器连接输入的字符序列 + * + * @param delimiter 分隔符 + * @return 连接字符序列的收集器 + */ + public static Collector joining(@NotNull CharSequence delimiter) { + return Collectors.joining(delimiter); + } + + + /** + * 返回一个收集器,该收集器连接输入的字符序列 + * + * @return 连接字符序列的收集器 + */ + public static Collector joining() { + return Collectors.joining(); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Set中 + * + * @param 输入元素的类型 + * @return 产生Set的收集器 + */ + public static Collector> toSet() { + return Collectors.toSet(); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到List中 + * + * @param 输入元素的类型 + * @return 产生List的收集器 + */ + public static Collector> toListCollector() { + return Collectors.toList(); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到指定类型的集合中 + * + * @param collectionFactory 用于创建集合的工厂函数 + * @param 输入元素的类型 + * @param 目标集合的具体类型 + * @return 产生指定类型集合的收集器 + */ + public static > Collector toCollection(@NotNull Supplier collectionFactory) { + return Collectors.toCollection(collectionFactory); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中,键由keyMapper提供,值为元素本身 + * + * @param keyMapper 用于产生键的映射函数 + * @param 输入元素的类型 + * @param 键的类型 + * @return 产生Map的收集器 + */ + public static Collector> toMap(Function keyMapper) { + return toMap(keyMapper, Function.identity()); + } + + + /** + * 返回一个收集器,该收集器将Map.Entry类型的输入元素累积到Map中 + * + * @param 输入元素的类型(必须是Map.Entry) + * @param 键的类型 + * @param 值的类型 + * @return 产生Map的收集器 + */ + public static , K, V> Collector> toMap() { + return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue); + } + + /** + * 对流中的每个元素应用过滤条件 + * + * @param predicate 用于测试元素是否满足条件的谓词 + * @return 过滤后的SuperStream实例 + */ + public SuperStream filter(Predicate predicate) { + return SuperStream.of(stream.filter(predicate)); + } + + /** + * 使用指定的收集器对流进行收集操作 + * + * @param collector 用于收集元素的收集器 + * @param 收集结果的类型 + * @param 收集器累加器的类型 + * @return 收集操作的结果 + */ + public R collect(Collector collector) { + return stream.collect(collector); + } + + /** + * 获取流的Spliterator + * + * @return 流的Spliterator实例 + */ + @NotNull + public Spliterator spliterator() { + return stream.spliterator(); + } + + /** + * 将每个元素映射为IntStream并展平结果 + * + * @param mapper 用于将元素映射为IntStream的函数 + * @return 展平后的IntStream + */ + public IntStream flatMapToInt(Function mapper) { + return stream.flatMapToInt(mapper); + } + + /** + * 检查流是否为并行流 + * + * @return 如果流是并行的则返回true,否则返回false + */ + public boolean isParallel() { + return stream.isParallel(); + } + + /** + * 获取流的迭代器 + * + * @return 流的Iterator实例 + */ + @NotNull + public Iterator iterator() { + return stream.iterator(); + } + + /** + * 对流中的每个元素执行指定的动作 + * + * @param action 要执行的动作函数 + */ + public void forEach(P1Function action) { + stream.forEach(action::call); + } + + /** + * 对流中的每个元素执行指定的动作,并传递索引 + * + * @param action 要执行的动作函数,接收元素和索引作为参数 + */ + public void forEach(P2Function action) { + AtomicInteger i22 = new AtomicInteger(0); + stream.forEach(i -> { + action.call(i, i22.getAndAdd(1)); + }); + } + + /** + * 对流中的每个元素执行指定的动作 + * + * @param action 要执行的动作函数 + */ + public void forEach(Consumer action) { + stream.forEach(action); + } + + /** + * 将每个元素映射为Stream并展平结果 + * + * @param mapper 用于将元素映射为Stream的函数 + * @param 映射后元素的类型 + * @return 展平后的Stream实例 + */ + public Stream flatMap(Function> mapper) { + return stream.flatMap(mapper); + } + + /** + * 返回一个串行流 + * + * @return 串行的SuperStream实例 + */ + @NotNull + public SuperStream sequential() { + return SuperStream.of(stream.sequential()); + } + + /** + * 跳过指定数量的元素 + * + * @param n 要跳过的元素数量 + * @return 跳过元素后的SuperStream实例 + */ + public SuperStream skip(long n) { + return SuperStream.of(stream.skip(n)); + } + + /** + * 使用指定的收集器对流进行收集操作 + * + * @param supplier 用于创建初始累加器的供应函数 + * @param accumulator 用于将元素添加到累加器的操作 + * @param combiner 用于合并两个累加器的操作 + * @param 收集结果的类型 + * @return 收集操作的结果 + */ + public R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner) { + return stream.collect(supplier, accumulator, combiner); + } + + /** + * 返回一个并行流 + * + * @return 并行的SuperStream实例 + */ + @NotNull + public SuperStream parallel() { + return SuperStream.of(stream.parallel()); + } + + /** + * 将每个元素映射为DoubleStream并展平结果 + * + * @param mapper 用于将元素映射为DoubleStream的函数 + * @return 展平后的DoubleStream + */ + public DoubleStream flatMapToDouble(Function mapper) { + return stream.flatMapToDouble(mapper); + } + + /** + * 将流转换为指定类型的数组 + * + * @param generator 用于创建数组的函数 + * @param 数组元素的类型 + * @return 转换后的数组 + */ + @NotNull + public A[] toArray(IntFunction generator) { + return stream.toArray(generator); + } + + /** + * 查找流中的第一个元素 + * + * @return 包含第一个元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional findFirst() { + return stream.findFirst(); + } + + /** + * 返回一个无序流 + * + * @return 无序的SuperStream实例 + */ + @NotNull + public SuperStream unordered() { + return SuperStream.of(stream.unordered()); + } + + /** + * 根据比较器查找流中的最小元素 + * + * @param comparator 用于比较元素的比较器 + * @return 包含最小元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional min(Comparator comparator) { + return stream.min(comparator); + } + + /** + * 查找流中的任意元素 + * + * @return 包含任意元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional findAny() { + return stream.findAny(); + } + + /** + * 注册一个关闭处理器,在流关闭时执行 + * + * @param closeHandler 关闭时要执行的Runnable + * @return 添加了关闭处理器的SuperStream实例 + */ + @NotNull + public SuperStream onClose(@NotNull Runnable closeHandler) { + return SuperStream.of(stream.onClose(closeHandler)); + } + + /** + * 将每个元素映射为LongStream并展平结果 + * + * @param mapper 用于将元素映射为LongStream的函数 + * @return 展平后的LongStream + */ + public LongStream flatMapToLong(Function mapper) { + return stream.flatMapToLong(mapper); + } + + /** + * 将流转换为指定类型的数组 + * + * @param clazz 数组元素的Class对象 + * @return 转换后的数组 + */ + @NotNull + @SuppressWarnings("unchecked") + public T[] toArray(Class clazz) { + return stream.toArray(i -> (T[]) Array.newInstance(clazz, i)); + } + + /** + * 将流转换为Object数组 + * + * @return 转换后的Object数组 + */ + @NotNull + public Object[] toArray() { + return stream.toArray(); + } + + /** + * 按顺序对流中的每个元素执行指定的动作 + * + * @param action 要执行的动作函数 + */ + public void forEachOrdered(Consumer action) { + stream.forEachOrdered(action); + } + + /** + * 关闭流并释放相关资源 + */ + public void close() { + stream.close(); + } + + /** + * 对流执行归约操作 + * + * @param accumulator 用于组合元素的二元操作符 + * @return 归约操作的结果,如果流为空则返回空Optional + */ + @NotNull + public Optional reduce(BinaryOperator accumulator) { + return stream.reduce(accumulator); + } + + /** + * 返回一个根据指定比较器排序的流 + * + * @param comparator 用于比较元素的比较器 + * @return 排序后的SuperStream实例 + */ + public SuperStream sorted(Comparator comparator) { + return SuperStream.of(stream.sorted(comparator)); + } + + /** + * 检查流中的所有元素是否都满足给定的谓词 + * + * @param predicate 用于测试元素的谓词 + * @return 如果所有元素都满足谓词或流为空则返回true,否则返回false + */ + public boolean allMatch(Predicate predicate) { + return stream.allMatch(predicate); + } + + /** + * 返回一个自然排序的流 + * + * @return 排序后的SuperStream实例 + */ + public SuperStream sorted() { + return SuperStream.of(stream.sorted()); + } + + /** + * 计算流中元素的数量 + * + * @return 流中元素的数量 + */ + public long count() { + return stream.count(); + } + + /** + * 将流中的每个元素通过映射函数转换 + * + * @param mapper 用于转换元素的映射函数 + * @param 映射后元素的类型 + * @return 转换后的SuperStream实例 + */ + public SuperStream map(Function mapper) { + return SuperStream.of(stream.map(mapper)); + } + + /** + * 对流执行归约操作 + * + * @param identity 归约操作的初始值 + * @param accumulator 用于组合元素的二元操作符 + * @return 归约操作的结果 + */ + public T reduce(T identity, BinaryOperator accumulator) { + return stream.reduce(identity, accumulator); + } + + /** + * 检查流中的所有元素都不满足给定的谓词 + * + * @param predicate 用于测试元素的谓词 + * @return 如果所有元素都不满足谓词则返回true,否则返回false + */ + public boolean noneMatch(Predicate predicate) { + return stream.noneMatch(predicate); + } + + /** + * 返回一个去重后的流 + * + * @return 去重后的SuperStream实例 + */ + public SuperStream distinct() { + return SuperStream.of(stream.distinct()); + } + + /** + * 根据比较器查找流中的最大元素 + * + * @param comparator 用于比较元素的比较器 + * @return 包含最大元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional max(Comparator comparator) { + return stream.max(comparator); + } + + /** + * 将流中的每个元素映射为double值 + * + * @param mapper 用于映射元素为double值的函数 + * @return 映射后的DoubleStream + */ + public DoubleStream mapToDouble(ToDoubleFunction mapper) { + return stream.mapToDouble(mapper); + } + + /** + * 限制流中元素的数量 + * + * @param maxSize 最大元素数量 + * @return 限制后的SuperStream实例 + */ + public SuperStream limit(long maxSize) { + return SuperStream.of(stream.limit(maxSize)); + } + + /** + * 将流中的每个元素映射为long值 + * + * @param mapper 用于映射元素为long值的函数 + * @return 映射后的LongStream + */ + public LongStream mapToLong(ToLongFunction mapper) { + return stream.mapToLong(mapper); + } + + /** + * 对流中的每个元素执行动作,然后返回原流 + * + * @param action 要执行的动作函数 + * @return 原始的SuperStream实例 + */ + public SuperStream peek(Consumer action) { + return SuperStream.of(stream.peek(action)); + } + + /** + * 对流执行归约操作 + * + * @param identity 归约操作的初始值 + * @param accumulator 用于组合元素的二元操作符 + * @param combiner 用于合并累加器的二元操作符 + * @param 累加器和结果的类型 + * @return 归约操作的结果 + */ + public U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) { + return stream.reduce(identity, accumulator, combiner); + } + + /** + * 将流中的每个元素映射为int值 + * + * @param mapper 用于映射元素为int值的函数 + * @return 映射后的IntStream + */ + public IntStream mapToInt(ToIntFunction mapper) { + return stream.mapToInt(mapper); + } + + /** + * 检查流中是否有任何元素满足给定的谓词 + * + * @param predicate 用于测试元素的谓词 + * @return 如果有任何元素满足谓词则返回true,否则返回false + */ + public boolean anyMatch(Predicate predicate) { + return stream.anyMatch(predicate); + } + + /** + * 获取被包装的基础Stream对象 + * + * @return 基础Stream对象 + */ + public Stream getStream() { + return stream; + } + + /** + * 将流中的元素收集到Map中,使用指定的键和值映射函数 + * + * @param keyMapper 用于生成键的映射函数 + * @param valueMapper 用于生成值的映射函数 + * @param 键的类型 + * @param 值的类型 + * @return 包含映射结果的Map + */ + public Map toAMap(Function keyMapper, Function valueMapper) { + return collect(toMap(keyMapper, valueMapper)); + } + + /** + * 将流中的元素收集到Map中,使用指定的键映射函数,值为元素本身 + * + * @param keyMapper 用于生成键的映射函数 + * @param 键的类型 + * @return 包含映射结果的Map + */ + public Map toAMap(Function keyMapper) { + return collect(toMap(keyMapper)); + } + + /** + * 将流中的元素收集到List中 + * + * @return 包含流中所有元素的List + */ + public List toAList() { + return collect(toListCollector()); + } + +} diff --git a/src/main/java/com/mingliqiye/utils/stream/SuprtStreamUtils.kt b/src/main/kotlin/com/mingliqiye/utils/stream/SuprtStreamUtils.kt similarity index 100% rename from src/main/java/com/mingliqiye/utils/stream/SuprtStreamUtils.kt rename to src/main/kotlin/com/mingliqiye/utils/stream/SuprtStreamUtils.kt diff --git a/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt b/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt index 6c4f1f4..f3e1dfc 100644 --- a/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt +++ b/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt @@ -16,444 +16,271 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile SystemUtil.kt - * LastUpdate 2026-03-27 09:35:40 + * LastUpdate 2026-10-20 18:54:24 * UpdateUser MingLiPro */ @file:JvmName("SystemUtils") package com.mingliqiye.utils.system -import java.lang.management.ManagementFactory import java.net.* +import java.util.* import com.mingliqiye.utils.random.Random.nextBytes as randomByte +private val UNIX_PREFIXES = arrayOf("Linux", "AIX", "SunOS", "Mac OS X", "FreeBSD") +private val HEX_UPPER: Array = Array(256) { "%02X".format(it) } + +private fun Enumeration?.toList(): List = + if (this == null) emptyList() else Collections.list(this) + /** * 操作系统名称属性,延迟初始化 */ val osName: String? by lazy { - System.getProperties().getProperty("os.name") + runCatching { System.getProperty("os.name") }.getOrNull() } /** - * 判断当前操作系统是否为Windows系统 - * - * @return 如果是Windows系统返回true,否则返回false + * 判断当前操作系统是否为 Windows */ val isWindows: Boolean by lazy { - osName != null && osName!!.startsWith("Windows") + osName?.startsWith("Windows") == true } /** - * 判断当前操作系统是否为Mac系统 - * - * @return 如果是Mac系统返回true,否则返回false + * 判断当前操作系统是否为 Mac */ val isMac: Boolean by lazy { - osName != null && osName!!.startsWith("Mac") + osName?.startsWith("Mac") == true } /** - * 判断当前操作系统是否为Unix/Linux系统 - * - * @return 如果是Unix/Linux系统返回true,否则返回false + * 判断当前操作系统是否为 Unix/Linux(含 macOS) */ val isUnix: Boolean by lazy { - if (osName == null) { - false - } else { - (osName!!.startsWith("Linux") || osName!!.startsWith("AIX") || osName!!.startsWith("SunOS") || osName!!.startsWith( - "Mac OS X" - ) || osName!!.startsWith( - "FreeBSD" - )) - } + val name = osName ?: return@lazy false + UNIX_PREFIXES.any { name.startsWith(it) } } /** - * JDK版本号属性,延迟初始化 + * JDK 版本号属性,延迟初始化 */ val jdkVersion: String? by lazy { - System.getProperty("java.specification.version") + runCatching { System.getProperty("java.specification.version") }.getOrNull() } /** - * Java版本号的整数形式属性,延迟初始化 + * Java 版本号的主版本整数,延迟初始化 + * + * 同时兼容 `1.8` 旧式版本号与 `9` / `17` / `100` 等新式版本号。 + * + * @throws IllegalStateException 无法解析出整数版本时抛出 */ val javaVersionAsInteger: Int by lazy { val version = jdkVersion - if (version == null || version.isEmpty()) { + if (version.isNullOrBlank()) { throw IllegalStateException( "Unable to determine Java version from property 'java.specification.version'" ) } - - val uversion: String = if (version.startsWith("1.")) { - if (version.length < 3) { - throw IllegalStateException( - "Invalid Java version format: $version" - ) - } - version[2] + "" - } else { - if (version.length < 2) { - throw IllegalStateException( - "Invalid Java version format: $version" - ) - } - version.take(2) - } - uversion.toInt() + val normalized = if (version.startsWith("1.")) version.substring(2) else version + val major = normalized.substringBefore('.').substringBefore('-') + major.toIntOrNull() + ?: throw IllegalStateException("Invalid Java version format: $version") } /** - * 判断当前JDK版本是否大于8 - * - * @return 如果JDK版本大于8返回true,否则返回false + * 判断当前 JDK 版本是否大于 8 */ val isJdk8Plus: Boolean by lazy { javaVersionAsInteger > 8 } /** - * 本地IP地址数组,延迟初始化 + * 本地 IPv4 地址数组,跳过回环、虚拟与未启用网卡 * - * @throws RuntimeException 当获取网络接口信息失败时抛出 + * @throws RuntimeException 网络接口枚举失败时抛出 */ val localIps: Array by lazy { try { - val ipList: MutableList = ArrayList() - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - // 跳过回环接口和虚拟接口 - if (networkInterface.isLoopback || networkInterface.isVirtual || !networkInterface.isUp) { - continue - } - - val addresses = networkInterface.inetAddresses - while (addresses.hasMoreElements()) { - val address = addresses.nextElement() - // 只获取IPv4地址 - if (address is Inet4Address) { - ipList.add(address.hostAddress) - } - } - } - - ipList.toTypedArray() + activeNetworkInterfaces() + .flatMap { it.inetAddresses.toList() } + .filterIsInstance() + .mapNotNull { it.hostAddress } + .toList() + .toTypedArray() } catch (e: SocketException) { throw RuntimeException("Failed to get local IP addresses", e) } } /** - * 本地IP地址列表,延迟初始化 + * 本地 IPv4 地址列表 */ -val localIpsByList: List by lazy { - localIps.toList() -} +val localIpsByList: List by lazy { localIps.toList() } /** - * 本地回环地址数组,延迟初始化 + * 本地回环地址数组;枚举失败时至少包含 `127.0.0.1` */ val loopbackIps: Array by lazy { - val strings: MutableList = ArrayList(3) - return@lazy try { - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - - // 只处理回环接口 - if (networkInterface.isLoopback && networkInterface.isUp) { - val addresses = networkInterface.inetAddresses - - while (addresses.hasMoreElements()) { - val address = addresses.nextElement() - strings.add(address.hostAddress) - } - } - } - strings.toTypedArray() - } catch (e: SocketException) { + try { + NetworkInterface.getNetworkInterfaces().toList() + .asSequence() + .filter { it.isLoopback && it.isUp } + .flatMap { it.inetAddresses.toList().asSequence() } + .mapNotNull { it.hostAddress } + .toList() + .toTypedArray() + } catch (_: SocketException) { arrayOf("127.0.0.1") } } /** - * 本地回环地址IP列表,延迟初始化 + * 本地回环地址列表 */ -val loopbackIpsByList: List by lazy { - loopbackIps.toList() -} +val loopbackIpsByList: List by lazy { loopbackIps.toList() } /** - * 获取当前进程的PID - * - * @return 进程ID,如果无法获取则返回-1 + * 当前进程 PID;获取失败返回 -1 */ val getPid: Long by lazy { - try { - val name = ManagementFactory.getRuntimeMXBean().name - val index = name.indexOf('@') - if (index > 0) { - name.take(index).toLong() - } else { - -1L - } - } catch (e: Exception) { - -1L - } + runCatching { ProcessHandle.current().pid() }.getOrElse { -1L } } /** - * 获取当前进程的PID字符串形式 - * - * @return 进程ID字符串,如果无法获取则返回"-1" + * 当前进程 PID 字符串;获取失败返回 "-1" */ val pidAsString: String by lazy { - try { - val name = ManagementFactory.getRuntimeMXBean().name - val index = name.indexOf('@') - if (index > 0) { - name.take(index) - } else { - "-1" - } - } catch (e: Exception) { - "-1" - } + val pid = getPid + if (pid == -1L) "-1" else pid.toString() } /** - * 获取计算机名 - * - * @return 计算机名,如果无法获取则返回"unknown" + * 计算机名;获取失败返回 "unknown" */ val computerName: String by lazy { - try { - var name = System.getenv("COMPUTERNAME") - if (name.isNullOrBlank()) { - name = System.getenv("HOSTNAME") - } - if (name.isNullOrBlank()) { - name = InetAddress.getLocalHost().hostName - } - name ?: "unknown" - } catch (e: Exception) { - "unknown" - } + getEnvVar("COMPUTERNAME") + ?: getEnvVar("HOSTNAME") + ?: runCatching { InetAddress.getLocalHost().hostName }.getOrNull()?.takeIf { it.isNotBlank() } + ?: "unknown" } /** - * 获取当前用户名 - * - * @return 当前用户名,如果无法获取则返回"unknown" + * 当前用户名;获取失败返回 "unknown" */ val userName: String by lazy { - try { - getEnvVar("USERNAME") ?: getEnvVar("USER") ?: System.getProperty("user.name") ?: "unknown" - } catch (e: SecurityException) { - "unknown" - } catch (e: Exception) { - "unknown" - } + getEnvVar("USERNAME") + ?: getEnvVar("USER") + ?: runCatching { System.getProperty("user.name") }.getOrNull()?.takeIf { it.isNotBlank() } + ?: "unknown" } -private fun getEnvVar(name: String): String? { - return try { - System.getenv(name)?.takeIf { it.isNotBlank() } - } catch (e: SecurityException) { - null - } -} +private fun getEnvVar(name: String): String? = runCatching { + System.getenv(name)?.takeIf { it.isNotBlank() } +}.getOrNull() /** - * 获取本机MAC地址的字节数组形式 + * 本机 MAC 地址字节数组 * - * @return MAC地址字节数组,如果无法获取则返回空数组 + * 未找到可用网卡时回退为 6 字节随机数,避免下游拿到空数组导致错误。 */ val macAddressBytes: ByteArray by lazy { - try { - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - - // 跳过回环接口和虚拟接口 - if (networkInterface.isLoopback || networkInterface.isVirtual || !networkInterface.isUp) { - continue - } - - val mac = networkInterface.hardwareAddress - if (mac != null && mac.isNotEmpty()) { - return@lazy mac - } - } - randomByte(6) - } catch (e: SocketException) { - randomByte(6) - } catch (e: Exception) { - randomByte(6) + val found = try { + activeNetworkInterfaces() + .mapNotNull { runCatching { it.hardwareAddress }.getOrNull() } + .firstOrNull { it.isNotEmpty() } + } catch (_: SocketException) { + null } + found ?: randomByte(6) } /** - * 获取本机MAC地址的十六进制字符串列表形式 - * - * @return MAC地址字符串列表,每个元素表示一个字节的十六进制值(大写),如果无法获取则返回空列表 + * 本机 MAC 地址的十六进制字符串列表(大写) */ val macAddressStringList: List by lazy { - val macBytes = macAddressBytes - if (macBytes.isEmpty()) { - return@lazy emptyList() - } - - macBytes.map { String.format("%02X", it) } + macAddressBytes.map { HEX_UPPER[it.toInt() and 0xFF] } } /** - * 获取本机MAC地址的格式化字符串形式(如 "00:11:22:33:44:55") - * - * @return 格式化的MAC地址字符串,如果无法获取则返回空字符串 + * 本机 MAC 地址的格式化字符串,如 `00:11:22:33:44:55` */ val macAddressFormattedString: String by lazy { - val macBytes = macAddressBytes - if (macBytes.isEmpty()) { - return@lazy "" - } - - macBytes.joinToString(":") { String.format("%02X", it) } + macAddressBytes.joinToString(":") { HEX_UPPER[it.toInt() and 0xFF] } } /** - * 获取所有网络接口的MAC地址映射 - * - * @return Map结构,key为网络接口名称,value为对应的MAC地址字节数组 + * 所有非回环、非虚拟网卡的 MAC 地址映射,key 为网卡名 */ val allMacAddresses: Map by lazy { try { - val result = mutableMapOf() - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - - // 跳过回环接口和虚拟接口 - if (networkInterface.isLoopback || networkInterface.isVirtual) { - continue + NetworkInterface.getNetworkInterfaces().toList() + .asSequence() + .filter { !it.isLoopback && !it.isVirtual } + .mapNotNull { ni -> + val mac = runCatching { ni.hardwareAddress }.getOrNull() + if (mac != null && mac.isNotEmpty()) ni.name to mac else null } - - val mac = networkInterface.hardwareAddress - if (mac != null && mac.isNotEmpty()) { - result[networkInterface.name] = mac - } - } - - result - } catch (e: SocketException) { - emptyMap() - } catch (e: Exception) { + .toMap() + } catch (_: SocketException) { emptyMap() } } /** - * 获取所有网络接口的MAC地址字符串列表映射 - * - * @return Map结构,key为网络接口名称,value为对应的MAC地址字符串列表 + * 所有网卡 MAC 地址的十六进制字符串列表映射 */ val allMacAddressesStringList: Map> by lazy { - allMacAddresses.mapValues { entry -> - entry.value.map { String.format("%02X", it) } - } + allMacAddresses.mapValues { (_, bytes) -> bytes.map { HEX_UPPER[it.toInt() and 0xFF] } } } /** - * 获取可用处理器数量的懒加载属性 + * 可用处理器数量 */ val availableProcessors: Int by lazy { Runtime.getRuntime().availableProcessors() } - -private var isLoadprotocol = false -private var protocol = "" +private fun activeNetworkInterfaces(): Sequence = + NetworkInterface.getNetworkInterfaces().toList().asSequence() + .filter { !it.isLoopback && !it.isVirtual && it.isUp } -/** - * 判断是否为开发模式(file协议) - */ -val isDevMode: Boolean by lazy { - protocol == "file" +private val protocol: String by lazy { + val target = ProtocolAnchor::class.java + val resourceName = target.simpleName + ".class" + val resource: URL = target.getResource(resourceName) + ?: throw IllegalStateException( + "Unable to locate resource '$resourceName' for class ${target.name}" + ) + resource.protocol } -/** - * 判断是否不为开发模式 - */ -val isNotDevMode: Boolean by lazy { - protocol != "file" -} -/** - * 判断是否为JAR模式 - */ -val isJarMode: Boolean by lazy { - protocol == "jar" -} +/** 是否为开发模式(file 协议) */ +val isDevMode: Boolean get() = protocol == "file" -/** - * 判断是否不为JAR模式 - */ -val isNotJarMode: Boolean by lazy { - protocol != "jar" -} +/** 是否不为开发模式 */ +val isNotDevMode: Boolean get() = protocol != "file" -/** - * 判断是否为WAR模式 - */ -val isWarMode: Boolean by lazy { - protocol == "war" -} +/** 是否为 JAR 模式 */ +val isJarMode: Boolean get() = protocol == "jar" -/** - * 判断是否不为WAR模式 - */ -val isNotMode: Boolean by lazy { - protocol != "war" -} +/** 是否不为 JAR 模式 */ +val isNotJarMode: Boolean get() = protocol != "jar" -/** - * 判断是否为JSWAR模式 - */ -val isJswarMode: Boolean by lazy { - protocol == "jswar" -} +/** 是否为 WAR 模式 */ +val isWarMode: Boolean get() = protocol == "war" -/** - * 判断是否不为JSWAR模式 - */ -val isNotJswarMode: Boolean by lazy { - protocol != "jswar" -} +/** 是否不为 WAR 模式 */ +val isNotWarMode: Boolean get() = protocol != "war" -/** - * 加载并获取资源协议 - * @param clazz 要获取协议的类对象,默认为null - * @return 返回资源的协议字符串 - */ -fun loadProtocol(clazz: Class<*>? = null): String { - // 如果已经加载过协议且clazz为null,则直接返回已缓存的协议 - if (isLoadprotocol && clazz == null) { - return protocol - } - val resource: URL? = clazz!!.getResource( - clazz.getSimpleName() + ".class" - ) - protocol = resource!!.protocol - return protocol.let { - isLoadprotocol = true - it - } -} +/** 是否为 JSWAR 模式 */ +val isJswarMode: Boolean get() = protocol == "jswar" + +/** 是否不为 JSWAR 模式 */ +val isNotJswarMode: Boolean get() = protocol != "jswar" + + +private object ProtocolAnchor