add methods

This commit is contained in:
Looly 2021-06-07 18:58:59 +08:00
parent b0e62df7c6
commit 671b6fa6a9

View File

@ -1,7 +1,15 @@
package cn.hutool.core.stream;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.CharsetUtil;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Spliterators;
import java.util.function.Function;
import java.util.function.UnaryOperator;
@ -17,11 +25,9 @@ import java.util.stream.StreamSupport;
public class StreamUtil {
@SafeVarargs
public static <T> Stream<T> of(T... values) {
if (null == values) {
return null;
}
return Stream.of(values);
public static <T> Stream<T> of(T... array) {
Assert.notNull(array, "Array must be not null!");
return Stream.of(array);
}
/**
@ -44,14 +50,58 @@ public class StreamUtil {
* @return {@link Stream}
*/
public static <T> Stream<T> of(Iterable<T> iterable, boolean parallel) {
if (null == iterable) {
return null;
}
Assert.notNull(iterable, "Iterable must be not null!");
return StreamSupport.stream(
Spliterators.spliterator(CollUtil.toCollection(iterable), 0),
parallel);
}
/**
* 按行读取文件为{@link Stream}
*
* @param file 路径
* @return {@link Stream}
*/
public static Stream<String> of(File file) {
return of(file, CharsetUtil.CHARSET_UTF_8);
}
/**
* 按行读取文件为{@link Stream}
*
* @param path 路径
* @return {@link Stream}
*/
public static Stream<String> of(Path path) {
return of(path, CharsetUtil.CHARSET_UTF_8);
}
/**
* 按行读取文件为{@link Stream}
*
* @param charset 编码
* @return {@link Stream}
*/
public static Stream<String> of(File file, Charset charset) {
Assert.notNull(file, "File must be not null!");
return of(file.toPath(), charset);
}
/**
* 按行读取文件为{@link Stream}
*
* @param path 路径
* @param charset 编码
* @return {@link Stream}
*/
public static Stream<String> of(Path path, Charset charset) {
try {
return Files.lines(path, charset);
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
/**
* 通过函数创建Stream
*
@ -68,9 +118,9 @@ public class StreamUtil {
/**
* 将Stream中所有元素以指定分隔符合并为一个字符串对象默认调用toString方法
*
* @param stream {@link Stream}
* @param delimiter 分隔符
* @param <T> 元素类型
* @param stream {@link Stream}
* @param delimiter 分隔符
* @param <T> 元素类型
* @return 字符串
*/
public static <T> String join(Stream<T> stream, CharSequence delimiter) {