mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
add CollStreamUtil
This commit is contained in:
parent
5c163941fe
commit
ede848ed07
@ -29,6 +29,7 @@ import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* 集合的stream操作封装
|
||||
@ -396,4 +397,25 @@ public class CollStreamUtil {
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 笛卡尔积<br>
|
||||
* 参考:https://www.baeldung-cn.com/java-cartesian-product-sets
|
||||
*
|
||||
* @param sets 集合列表
|
||||
* @param index 索引
|
||||
* @return 笛卡尔积
|
||||
*/
|
||||
public static Stream<List<Object>> cartesianProduct(final List<List<Object>> sets, final int index) {
|
||||
if (index == sets.size()) {
|
||||
return Stream.of(ListUtil.zero());
|
||||
}
|
||||
final List<Object> currentSet = sets.get(index);
|
||||
return currentSet.stream().flatMap(element -> cartesianProduct(sets, index + 1)
|
||||
.map(list -> {
|
||||
final List<Object> newList = new ArrayList<>(list);
|
||||
newList.add(0, element);
|
||||
return newList;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
@ -16,10 +16,10 @@
|
||||
|
||||
package org.dromara.hutool.core.collection;
|
||||
|
||||
import org.dromara.hutool.core.map.MapUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.ToString;
|
||||
import org.dromara.hutool.core.map.MapUtil;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@ -320,6 +320,25 @@ public class CollStreamUtilTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cartesianProductTest() {
|
||||
final List<List<Object>> sets = new ArrayList<>();
|
||||
sets.add(ListUtil.of(10, 20));
|
||||
sets.add(ListUtil.of("John", "Jack"));
|
||||
sets.add(ListUtil.of('I', 'J'));
|
||||
|
||||
final List<List<Object>> collect = CollStreamUtil.cartesianProduct(sets, 0).collect(Collectors.toList());
|
||||
Assertions.assertEquals(8, collect.size());
|
||||
Assertions.assertEquals("[10, John, I]", collect.get(0).toString());
|
||||
Assertions.assertEquals("[10, John, J]", collect.get(1).toString());
|
||||
Assertions.assertEquals("[10, Jack, I]", collect.get(2).toString());
|
||||
Assertions.assertEquals("[10, Jack, J]", collect.get(3).toString());
|
||||
Assertions.assertEquals("[20, John, I]", collect.get(4).toString());
|
||||
Assertions.assertEquals("[20, John, J]", collect.get(5).toString());
|
||||
Assertions.assertEquals("[20, Jack, I]", collect.get(6).toString());
|
||||
Assertions.assertEquals("[20, Jack, J]", collect.get(7).toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 班级类
|
||||
*/
|
||||
|
Loading…
x
Reference in New Issue
Block a user