Browse Source

fix: optimize split for list

easepan 5 years ago
parent
commit
8913aeaf33

+ 13 - 0
hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java

@@ -1118,6 +1118,19 @@ public class CollUtil {
 	/**
 	 * 对集合按照指定长度分段,每一个段为单独的集合,返回这个集合的列表
 	 *
+	 * @param <T> 集合元素类型
+	 * @param list 列表
+	 * @param size 每个段的长度
+	 *
+	 * @return 分段列表
+	 */
+	public static <T> List<List<T>> splitList(List<T> list, int size) {
+		return ListUtil.split(list, size);
+	}
+
+	/**
+	 * 对集合按照指定长度分段,每一个段为单独的集合,返回这个集合的列表
+	 *
 	 * @param <T>        集合元素类型
 	 * @param collection 集合
 	 * @param size       每个段的长度

+ 25 - 0
hutool-core/src/main/java/cn/hutool/core/collection/ListUtil.java

@@ -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;
+	}
 }

+ 27 - 0
hutool-core/src/test/java/cn/hutool/core/collection/ListUtilTest.java

@@ -1,13 +1,40 @@
 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");
 		final List<String> filter = ListUtil.filter(a, str -> "edit" + str);