list,map拆分方法

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、问题描述

在批量操作时,经常遇到list,map大小超大,批量操作数据库或Redis时还需要进行拆分。

2、相关代码

a、Map拆分

 1 /**
 2      * 描述:分割Collection
 3      * @param collection 原始数据
 4      * @param pageSize 每个set数量
 5      * @return ListList<T>
 6      */
 7     public static <T> List<List<T>> splitCollectionToList(Collection<T> collection, int pageSize){
 8         if(collection == null || collection.isEmpty()){
 9             return Collections.emptyList();
10         }
11         pageSize = pageSize == 0?10000:pageSize;
12         List<T> list = new ArrayList(collection);
13         List<List<T>> newSet = new ArrayList<>();
14         int st = 0;
15         int size = collection.size();
16         while(size>pageSize){
17             newSet.add(new ArrayList(list.subList(st, st+pageSize)));
18             st+=pageSize;
19             size-=pageSize;
20         }
21         newSet.add(new ArrayList(list.subList(st, collection.size())));
22         return newSet;
23     }

b、List拆分

 1 /**
 2      * 描述:分割Map
 3      * @param map 原始数据
 4      * @param pageSize 每个map数量
 5      * @return ListList<Map<K, V>>
 6      */
 7     public static <K, V> List<Map<K, V>> splitMap(Map<K, V> map, int pageSize){
 8         if(map == null || map.isEmpty()){
 9             return Collections.emptyList();
10         }
11         pageSize = pageSize == 0?10000:pageSize;
12         List<Map<K, V>> newList = new ArrayList<>();
13         int j = 0;
14         for(K k :map.keySet()){
15             if(j%pageSize == 0) {
16                 newList.add(new HashMap<>());
17             }
18             newList.get(newList.size()-1).put(k, map.get(k));
19             j++;
20         }
21         return newList;
22     }

 

posted @ 2018-06-02 11:40  mao2080  阅读(1642)  评论(0)    收藏  举报