有时候,我们需要将大的集合按指定的数量分割成若干个小集合。(比如:集合作为SQL中IN的参数,而SQL又有长度限制,所以需要分批分几次进行查询)

虽然此需求感觉不常见,但偶也写过几次类似的方法,故记录之。

更新于2017年:其实Guava库有个已有的方法实现此需求:Lists.partition(List<T> list, int size)

 

v2,更新于2016-01-20

v1的代码使用后发现有问题,如果对分组后的一子集作删除操作,其他子集用迭代器遍历时会出现ConcurrentModificationException。

修改后的代码如下:

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(new ArrayList(list.subList(count, (count + quantity) > list.size() ? list.size() : count + quantity)));
            count += quantity;
        }
        
        return wrapList;
    }
    
}
View Code

相关文章:

  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
  • 2021-08-04
  • 2022-12-23
  • 2021-11-23
猜你喜欢
  • 2021-06-02
  • 2022-01-01
  • 2022-12-23
  • 2021-09-11
  • 2021-09-20
  • 2022-12-23
  • 2021-12-28
相关资源
相似解决方案