Partition a list in sub-lists, with max size equal to 'batchSize' parameter. - Java java.util

Java examples for java.util:List Sub List

Description

Partition a list in sub-lists, with max size equal to 'batchSize' parameter.

Demo Code


//package com.book2s;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "book2s.com");
        Integer batchSize = 42;/* ww  w.  j  a  v  a  2  s  .  com*/
        System.out.println(partition(list, batchSize));
    }

    /**
     * Partition a list in sub-lists, with max size equal to 'batchSize' parameter.
     * 
     * @param list
     *          The list to be partitioned.
     * @param batchSize
     *          The batch size, representing the maximum size allowed for a sub-list.
     * @return
     */
    public static <E> List<List<E>> partition(List<E> list,
            Integer batchSize) {
        List<List<E>> retObj = new ArrayList<List<E>>();

        if (isNotEmpty(list)) {
            retObj = new ArrayList<List<E>>();
            List<E> currentList = null;

            for (int i = 0; i < list.size(); i++) {
                if (i % batchSize == 0) {
                    currentList = new ArrayList<E>();
                    retObj.add(currentList);
                }
                currentList.add(list.get(i));
            }
        }
        return retObj;
    }

    /**
     * Check if set isn't empty.
     * 
     * @param set
     *          The set to be tested.
     * @return <code>true</code> is not empty, <code>false</code> otherwise.
     */
    public static <E> boolean isNotEmpty(Set<E> set) {
        return set != null && !set.isEmpty();
    }

    /**
     * This method checks if the list is not null and have elements.
     * 
     * @param <E>
     * 
     * @param list
     *          the list to check
     * @return true/false
     */
    public static <E> boolean isNotEmpty(List<E> list) {
        return list != null && !list.isEmpty();
    }

    /**
     * This method checks if the list is not null and have elements.
     * 
     * @param <E>
     * 
     * @param list
     *          the list to check
     * @return true/false
     */
    public static <E> boolean isNotEmpty(E[] list) {
        return list != null && list.length > 0;
    }

    /**
     * Check if set is empty.
     * 
     * @param set
     * @return
     */
    public static <E> boolean isEmpty(Set<E> set) {
        return !isNotEmpty(set);
    }

    public static <E> boolean isEmpty(List<E> list) {
        return !isNotEmpty(list);
    }

    public static <E> boolean isEmpty(E[] list) {
        return !isNotEmpty(list);
    }
}

Related Tutorials