split List by size - Java java.util

Java examples for java.util:List Split

Description

split List by size

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 size = 42;
        System.out.println(split(list, size));
    }//from   www .java 2 s. com

    public static <T> List<List<T>> split(List<T> list, int size) {
        List<List<T>> result = new ArrayList<>();

        int n = list.size() / size;
        int r = list.size() % size;

        for (int i = 0; i < n; i++) {
            List<T> split = new ArrayList<>();
            for (int j = i * size; j < i * size + size; j++) {
                split.add(list.get(j));
            }
            result.add(split);
        }

        if (r > 0) {
            List<T> rest = new ArrayList<>();
            for (int i = n * size; i < list.size(); i++) {
                rest.add(list.get(i));
            }
            result.add(rest);
        }

        return result;
    }
}

Related Tutorials