Java List按指定size分批

/**
 * 将原始list按照MAX_LIST_SIZE分组
 * @param list
 * @return
 */
public static  List> generateListGroup(List list, int maxListSize) {
    List> listGroup = Lists.newArrayList();
    if (CollectionUtils.isEmpty(list) || list.size() <= maxListSize) {
        listGroup.add(list);
    } else {
        int pages = (int) Math.ceil((double)list.size() / (double)maxListSize);
        for (int i = 0; i < pages; i++) {
            int fromIndex = i * maxListSize;
            int toIndex = (i + 1) * maxListSize > list.size() ? list.size()
                    : (i + 1) * maxListSize;
            List subList = list.subList(fromIndex, toIndex);
            listGroup.add(subList);
        }
    }
    return listGroup;
}

 Guava中提供了类似功能的实现

List numList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List> partList = Lists.partition(numList, 3);

 

你可能感兴趣的:(Java List按指定size分批)