mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
添加flat方法
This commit is contained in:
parent
13fe08c73f
commit
844b05cc35
@ -2363,13 +2363,14 @@ public class CollUtil {
|
||||
* @param collection 需要解构的集合
|
||||
* @return 解构后的集合
|
||||
*/
|
||||
public static List<Object> flat(Collection<?> collection) {
|
||||
public static <T> List<T> flat(Collection<?> collection) {
|
||||
return flat(collection, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解构多层集合
|
||||
* 例如:List<List<List<String>>> 解构成 List<String>
|
||||
* 例如:例如:{@code List<List<List<String>>> 解构成 List<String>}
|
||||
* <p>
|
||||
* skipNull如果为true, 则解构后的集合里不包含null值,为false则会包含null值。
|
||||
*
|
||||
* @param collection 需要结构的集合
|
||||
@ -2377,7 +2378,7 @@ public class CollUtil {
|
||||
* @return 解构后的集合
|
||||
*/
|
||||
@SuppressWarnings({"unchecked"})
|
||||
public static List<Object> flat(Collection<?> collection, boolean skipNull) {
|
||||
public static <T> List<T> flat(Collection<?> collection, boolean skipNull) {
|
||||
LinkedList<Object> queue = new LinkedList<>(collection);
|
||||
|
||||
List<Object> result = new ArrayList<>();
|
||||
@ -2385,14 +2386,16 @@ public class CollUtil {
|
||||
while (!queue.isEmpty()) {
|
||||
Object t = queue.removeFirst();
|
||||
|
||||
if (skipNull && t == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (t instanceof Collection) {
|
||||
queue.addAll((Collection<?>) t);
|
||||
} else if (skipNull && t == null) {
|
||||
continue;
|
||||
} else {
|
||||
result.add(t);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return (List<T>) result;
|
||||
}
|
||||
}
|
||||
|
@ -489,14 +489,15 @@ public interface TransformableWrappedStream<T, S extends TransformableWrappedStr
|
||||
|
||||
/**
|
||||
* 如果当前元素是集合,则会将集合中的元素解构出来
|
||||
* 例如:List<List<List<String>>> 解构成 List<String>
|
||||
* @param clazz 解构后元素的类型
|
||||
* @param <R> 函数执行后返回的类型
|
||||
* 例如:{@code List<List<List<String>>> 解构成 List<String>}
|
||||
*
|
||||
* @param <R> 函数执行后返回的List里面的类型
|
||||
* @return EasyStream 一个流
|
||||
*/
|
||||
default <R> EasyStream<R> flatObj(Class<R> clazz) {
|
||||
return EasyStream.of(CollUtil.flat(nonNull().collect(Collectors.toList()))).map(clazz::cast);
|
||||
default <R> EasyStream<R> flat() {
|
||||
return EasyStream.of(CollUtil.flat(nonNull().collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region ============ map ============
|
||||
|
@ -723,7 +723,7 @@ public class AbstractEnhancedWrappedStreamTest {
|
||||
Arrays.asList("j", "k", "l")
|
||||
)
|
||||
);
|
||||
List<String> r = EasyStream.of(list).flatObj(String.class).toList();
|
||||
List<String> r = EasyStream.of(list).<String>flat().toList();
|
||||
Assertions.assertArrayEquals(new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"}, r.toArray());
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user