Split a List to List of List - Java java.util

Java examples for java.util:List Operation

Description

Split a List to List of List

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        int subListNumber = 1;
        System.out.println(splitList(list, subListNumber));
    }/*  ww  w. jav a2  s .c  o m*/


    public static <T> List<List<T>> splitList(List<T> list,
            int subListNumber) {
        List<List<T>> splitted = new ArrayList<List<T>>();
        if (list == null || list.size() == 0)
            return splitted;
        int listSize = list.size();
        int subSize = Math.max(listSize / (subListNumber - 1), 1);
        for (int i = 0; i < listSize; i += subSize) {
            splitted.add(new ArrayList<T>(list.subList(i,
                    Math.min(listSize, i + subSize))));
        }
        return splitted;
    }
}

Related Tutorials