Here you can find the source of subCollection(Collection
public static <T> Collection<T> subCollection(Collection<T> col, int amount)
//package com.java2s; //License from project: Apache License import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class Main { public static <T> Collection<T> subCollection(Collection<T> col, int amount) { if (!isNullOrEmpty(col) && (col.size() > amount)) { ArrayList<T> list = new ArrayList<T>(col); return list.subList(0, amount); }// w w w . j a v a 2s .co m return col; } /** * Performs a thorough null and empty check. This asserts that a given collection is null, empty or only consists of null values. * * @param col * @return asserts that a given collection is null, empty or only consists of null values. */ public static boolean isNullOrEmpty(Collection<?> col) { if ((col == null) || col.isEmpty()) return true; else { try { for (Iterator<?> iterator = col.iterator(); iterator.hasNext();) { if (iterator.next() != null) { return false; } } } catch (NullPointerException e) { // guard against null during concurrent modifications return false; } return true; } } /** * creates a list of lists, each of which is up to the value of threshold in length. * * @param <T> * @param initial * @param threshold * @return */ public static <T> List<List<T>> subList(List<T> initial, int threshold) { ArrayList<List<T>> list = new ArrayList<List<T>>(); if (initial != null) { if (initial.size() <= threshold) { list.add(initial); } else { int factor = initial.size() / threshold; for (int i = 0; i < (factor + 1); i++) { list.add(limit(initial, i * threshold, threshold)); } } } return list; } /** * Performs a safe limit on a given list. checks wether offset and amount are within bounds. If the offset is out of bounds, limit will automatically adapt by * substracting amount from the lists size. If amount is larger than initial's size, initia will be returned in its entirity. * * * @param <T> * @param initial * @param offset * @param amount * @return a safely limited version of initial. */ public static <T> List<T> limit(List<T> initial, int offset, int amount) { if (isNullOrEmpty(initial)) { return new ArrayList<T>(); } else if (amount > initial.size()) { return initial; } int lower = (int) ((offset < initial.size()) ? offset : (((initial.size() - offset) < 0) ? 0 : (initial.size() - offset))); int upper = amount + lower; List<T> resultSet = new ArrayList<T>( initial.subList((lower > initial.size()) ? (initial.size() - amount) : lower, (upper > initial.size()) ? initial.size() : upper)); return resultSet; } }