List集合按数量分组
工具类 CollectionGroupUtil
package com.ssish.wxmall.common.data;
import java.util.ArrayList;
import java.util.List;
public class CollectionGroupUtil {
public static List groupListByQuantity(List list, int quantity) {
if (list == null || list.size() == 0) {
return list;
}
if (quantity <= 0) {
new IllegalArgumentException("Wrong quantity.");
}
List wrapList = new ArrayList();
int count = 0;
while (count < list.size()) {
wrapList.add(list.subList(count, (count + quantity) > list.size() ? list.size() : count + quantity));
count += quantity;
}
return wrapList;
}
}
调用
List<ActiveDataTemp> list = activeDataTempMapper.selectByExample(example);
if(!CollectionUtils.isEmpty(list)){
Collections.shuffle(list); //随机排序
List<List<ActiveDataTemp>> groupList = CollectionGroupUtil.groupListByQuantity(list, 4); //每4条一组
baseResult.setContent(list);
}
输出结果
{
"returnCode": "0000",
"returnMsg": null,
"content": [
[
{
"id": 47,
"content": "恭喜尾号8278谢老师 出单君康金生金世黄金版 1000000元",
"type": "1",
"status": "1"
},
{
"id": 32,
"content": "恭喜尾号2271董老师出单金生金世黄金版 50000元",
"type": "1",
"status": "1"
},
{
"id": 34,
"content": "恭喜尾号7592陈老师出单君康金生金世 500000元",
"type": "1",
"status": "1"
},
{
"id": 51,
"content": "恭喜尾号3840黄老师 出单君康金生金世黄金版 500000元",
"type": "1",
"status": "1"
}
],
[
{
"id": 49,
"content": "恭喜尾号8220崔老师 出单君康金生金世黄金版 2000000元",
"type": "1",
"status": "1"
},
{
"id": 43,
"content": "恭喜尾号2330方老师 出单信泰如意尊2.0版 600000元",
"type": "1",
"status": "1"
}
]
]
}