Java Array Split split(Collection collection, C[] array, int pageSize)

Here you can find the source of split(Collection collection, C[] array, int pageSize)

Description

split

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static <T, C extends Collection<T>> C[] split(Collection<T> collection, C[] array, int pageSize) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;
import java.util.Collection;

import java.util.Map;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T, C extends Collection<T>> C[] split(Collection<T> collection, C[] array, int pageSize) {

        try {//from w w  w  . j a va  2s.  c o m

            int size = (int) Math.ceil((collection.size() / (double) pageSize));

            Object[] toReturn = new Object[size];
            int index = 0;

            C currentCollection = (C) array.getClass().getComponentType().newInstance();
            int count = 0;

            for (T obj : collection) {
                currentCollection.add(obj);
                count++;
                if (count == pageSize) {
                    toReturn[index++] = currentCollection;
                    currentCollection = (C) array.getClass().getComponentType().newInstance();
                    count = 0;
                }
            }

            if (count > 0) {
                toReturn[index++] = currentCollection;
            }

            return (C[]) Arrays.copyOf(toReturn, size, array.getClass());

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static int size(Collection<?> collection) {
        return isEmpty(collection) ? 0 : collection.size();
    }

    /**
     * Test se la collection IS EMPTY
     * 
     * @param collection
     * @return
     */
    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }
}

Related

  1. split(byte[] array, int index, int len, byte value)
  2. split(byte[] pattern, byte[] src)
  3. split(byte[] source, int c)
  4. split(final int[] array)
  5. split(int splitBefore, byte[] source)
  6. split(String string, String delim, String[] a)
  7. splitAndPad(byte[] byteArray, int blocksize)