java工具類-列表分段處理


java.util.List 分段

使用google的guava類庫對List分段處理

     List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        List<List<Integer>> subSets = Lists.partition(intList, 3);
List<Integer> last = subSets.get(2);

  原理是內部封裝着我們要分段的List的引用,在subSets.get(index) 語句時,對參數List.subList()動態處理 

對集合的處理

        Collection<Integer> intCollection = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        Iterable<List<Integer>> subSets = Iterables.partition(intCollection, 3);
        List<Integer> firstPartition = subSets.iterator().next();

  使用iterable進行遍歷,iterator.next()方法,內部是使用固定size大小的數組循環狀態size次數據,然后返回數據

 

使用apache common工具的的List分段處理方法

        ArrayList<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        List<List<Integer>> subSets2 = ListUtils.partition(intList, 3);

  這個方法和guava包的列表分段方法原理是相同的

 

 

 

自定義泛型方法進行分頁

    /**
     * 列表數據分組
     * @param source 源數據
     * @param size 根據大小分組
     * @param <T> 泛型
     * @return
     */
    public static <T> List<List<T>>  averageAssign(List<T> source, int size){
        List<List<T>> result = new ArrayList<>();
        int offset=0;
        boolean isZero = source.size()%size==0;
        int totalPage = source.size()/size + 1;
        int totalSize = source.size();
        while(totalPage-1>=offset){
            List<T> subList = null;
            if(offset == totalPage-1){
                if(isZero){
                    break;
                }
                //最后一段的處理
                subList = source.subList(size * offset, totalSize);
            }else{
                subList = source.subList(size * offset, size * (offset + 1));
            }
            offset++;
            result.add(subList);
        }
        return result;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM