Class StreamUtil

java.lang.Object
com.sure.tool.util.StreamUtil

public final class StreamUtil extends Object
流工具类,参考 Hutool 的 StreamUtil 设计。

提供数组 / 集合 / 迭代器 / Optional 转流、多流合并、空安全等常用静态方法, 全部方法对 null 输入安全(不会抛 NPE)。

Since:
1.19.0
Author:
suretool
  • Method Details

    • of

      @SafeVarargs public static <T> Stream<T> of(T... values)
      变参或数组转流(null 安全)。

      示例:StreamUtil.of("a", "b", "c");StreamUtil.of(null) 返回空流。

      Parameters:
      values - 元素数组,可为 null
      Returns:
      元素流;values 为 null 返回空流
    • of

      public static <T> Stream<T> of(Collection<T> collection)
      集合转流(null 安全)。

      示例:StreamUtil.of(list);StreamUtil.of(null) 返回空流。

      Parameters:
      collection - 集合,可为 null
      Returns:
      集合元素流;null 返回空流
    • of

      public static <T> Stream<T> of(Iterable<T> iterable)
      迭代器转流(null 安全)。

      示例:StreamUtil.of(iterable);StreamUtil.of(null) 返回空流。

      Parameters:
      iterable - 可迭代对象,可为 null
      Returns:
      元素流;null 返回空流
    • of

      public static <T> Stream<T> of(Optional<T> optional)
      Optional 转流:有值则单元素流,否则空流(Java 9 Stream.ofNullable 语义)。

      示例:StreamUtil.of(Optional.of("x"));StreamUtil.of(Optional.empty()) 返回空流。

      Parameters:
      optional - Optional 值,可为 null
      Returns:
      元素流;null 或空 Optional 返回空流
    • concat

      @SafeVarargs public static <T> Stream<T> concat(Stream<? extends T>... streams)
      合并多个流(null 流自动跳过)。

      示例:StreamUtil.concat(Stream.of(1), null, Stream.of(2)) 产生 1、2。

      Parameters:
      streams - 流数组,可为 null,元素可为 null
      Returns:
      合并后的流;全部为空返回空流
    • nullToEmpty

      public static <T> Stream<T> nullToEmpty(Stream<T> stream)
      空安全:null 流转换为空流。

      示例:StreamUtil.nullToEmpty(null) 返回空流。

      Parameters:
      stream - 流,可为 null
      Returns:
      原流;null 返回空流
    • empty

      public static <T> Stream<T> empty()
      返回空流。

      示例:StreamUtil.empty() 等价于 Stream.empty()。

      Returns:
      空流