java 等分行表示_【Java】实现list等分

事件起因

博主在学习 Python 爬虫的时候,需要将一个 list 等分成 n 个 list 。

由于能力有限,自己也没有更好的实现方式,所以就现成的拿了别人的代码直接用。

def splist(l, s):

return [l[i:i+s] for i in range(len(l)) if i%s==0]

然而很不巧的的是,项目过程中又碰到了这个问题,而且这次用的是 Java !!!

虽然说处理的过程是有类似的地方,但真动手写起来还是比较棘手的。毕竟 Java 没有像 Python 这些丰富的库函数。

网上我也找过一些类似的方法,但都不是很满意,所以还是自己花时间折腾来造造轮子。

实现代码

直接附上自己写的代码(轻喷):

/**

* 平分list成n份 数据量尽可能相等

* @param list 需要平分的list

* @param n 平分成n分

* @return

*/

public static List> splitList(List list, int n) {

List> strList = new ArrayList<>();

if (list == null) return strList;

int size = list.size();

int quotient = size / n; // 商数

int remainder = size % n; // 余数

int offset = 0; // 偏移量

int len = quotient > 0 ? n : remainder; // 循环长度

int start = 0; // 起始下标

int end = 0; // 结束下标

List tempList = null;

for (int i = 0; i < len; i++) {

if (remainder != 0) {

remainder--;

offset = 1;

} else {

offset = 0;

}

end = start + quotient + offset;

tempList = list.subList(start, end);

start = end;

strList.add(tempList);

}

return strList;

}

代码用例

代码用例如下:

public static void main(String[] args) {

List integerList = new ArrayList<>();

// 原始数据:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

for (int i = 0; i < 14; i++) {

integerList.add(i);

}

List> splitList = splitList(integerList, 10); // 分成10等份

System.out.println(splitList);

}

按10等份分组后输出的结果如下:

[[0, 1], [2, 3], [4, 5], [6, 7], [8], [9], [10], [11], [12], [13]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值