在某些场景中,需要批量执行数据,可以通过数据库分页查询,也可以通过java来对集合进行分页。将list(或其他集合)拆分成多份,java传统的集合操作中并没有这样的方法。常见方法有:
1、手动分片:
/**
* 将一个list均分成n个list,主要通过偏移量来实现的
*
* @param source
* @return
*/
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remaider = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List<T> value = null;
if (remaider > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remaider--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}
2、google guava分片:
import com.google.common.collect.Lists;
public class ListsPartitionTest1 {
public static void main(String[] args) {
List<String> ls = Arrays.asList("1,2,3,4,5,6,7,8,9,1,2,4,5,6,7,7,6,6,6,6,6,66".split(","));
System.out.println(Lists.partition(ls, 20));
}
}
再如:
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
public class ListsTest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// 按大小 2 拆分
List<List<Integer>> listPartitionList = Lists.partition(list, 2);
System.out.println("原 List:");
System.out.println(list);
System.out.println("拆分后:");
for (List<Integer> partition: listPartitionList) {
System.out.println(partition);
}
}
}
原 List:
[1, 2, 3, 4, 5]
拆分后:
[1, 2]
[3, 4]
[5]
3、apache commons collections分片:
import org.apache.commons.collections4.ListUtils;
public class ListsPartitionTest2 {
public static void main(String[] args) {
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
System.out.println(ListUtils.partition(intList, 3));
}
}
4、使用Java8 stream流 partition by,partitioningBy是一种特殊的分组,只会分成两组
List<Integer> nums = Lists.newArrayList(1,1,8,2,3,4,5,6,7,9,10);
Map<Boolean,List<Integer>> numMap= numList.stream().collect(Collectors.partitioningBy(num -> num > 5));
System.out.println(numMap);
{false=[2, 3, 4, 5], true=[8, 6, 7, 9, 10]}