mirror of
https://gitee.com/dromara/hutool.git
synced 2025-04-05 17:37:59 +08:00
!194 优化针对list的split方法
Merge pull request !194 from easepan/hotfix/optimize-collutil-split
This commit is contained in:
commit
cc59412909
@ -1115,6 +1115,19 @@ public class CollUtil {
|
||||
return sub(new ArrayList<>(list), start, end, step);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对集合按照指定长度分段,每一个段为单独的集合,返回这个集合的列表
|
||||
*
|
||||
* @param <T> 集合元素类型
|
||||
* @param list 列表
|
||||
* @param size 每个段的长度
|
||||
*
|
||||
* @return 分段列表
|
||||
*/
|
||||
public static <T> List<List<T>> splitList(List<T> list, int size) {
|
||||
return ListUtil.split(list, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对集合按照指定长度分段,每一个段为单独的集合,返回这个集合的列表
|
||||
*
|
||||
|
@ -494,4 +494,29 @@ public class ListUtil {
|
||||
public static <T> List<T> empty() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对集合按照指定长度分段,每一个段为单独的集合,返回这个集合的列表
|
||||
*
|
||||
* @param <T> 集合元素类型
|
||||
* @param list 列表
|
||||
* @param size 每个段的长度
|
||||
*
|
||||
* @return 分段列表
|
||||
*/
|
||||
public static <T> List<List<T>> split(List<T> list, int size) {
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<List<T>> result = new ArrayList<>(list.size() / size + 1);
|
||||
int offset = 0;
|
||||
for (int toIdx = size; toIdx <= list.size(); offset = toIdx, toIdx += size) {
|
||||
result.add(list.subList(offset, toIdx));
|
||||
}
|
||||
if (offset < list.size()) {
|
||||
result.add(list.subList(offset, list.size()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,39 @@
|
||||
package cn.hutool.core.collection;
|
||||
|
||||
import cn.hutool.core.date.StopWatch;
|
||||
import cn.hutool.core.lang.Console;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ListUtilTest {
|
||||
|
||||
@Test
|
||||
public void split() {
|
||||
List<String> list = new ArrayList<>();
|
||||
CollUtil.padRight(list, RandomUtil.randomInt(1000_0000, 1_0000_0000), "test");
|
||||
|
||||
int size = RandomUtil.randomInt(10, 1000);
|
||||
Console.log("\nlist size: {}", list.size());
|
||||
Console.log("partition size: {}\n", size);
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
|
||||
stopWatch.start("CollUtil#split");
|
||||
List<List<String>> CollSplitResult = CollUtil.split(list, size);
|
||||
stopWatch.stop();
|
||||
|
||||
stopWatch.start("ListUtil#split");
|
||||
List<List<String>> ListSplitResult = ListUtil.split(list, size);
|
||||
stopWatch.stop();
|
||||
|
||||
Assert.assertEquals(CollSplitResult, ListSplitResult);
|
||||
|
||||
Console.log(stopWatch.prettyPrint());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterTest(){
|
||||
List<String> a = ListUtil.toLinkedList("1", "2", "3");
|
||||
|
Loading…
Reference in New Issue
Block a user