Java List Sub List subList(List list, int size)

Here you can find the source of subList(List list, int size)

Description

Extract n items from the list, if the n>list.size, return all.

License

Open Source License

Parameter

Parameter Description
biosamples a parameter
size a parameter

Declaration

public static <T> List<T> subList(List<T> list, int size) 

Method Source Code

//package com.java2s;
/*/*from   w w  w .  j  a va  2  s .  co  m*/
 * Spirit, a study/biosample management tool for research.
 * Copyright (C) 2018 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91,
 * CH-4123 Allschwil, Switzerland.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 * @author Joel Freyss
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Extract n items from the list, if the n>list.size, return all.
     * Otherwise return n elements using a progressive incrementation
     * @param biosamples
     * @param size
     * @return
     */
    public static <T> List<T> subList(List<T> list, int size) {
        if (size >= list.size())
            return list;

        List<T> res = new ArrayList<T>();
        //We choose alpha such as sum(1+(alpha*i), i, 0, n-1)) = list.size
        int alpha = -2 * (size - list.size() - 1) / (size * (size - 1));
        int index = 0;
        for (int i = 0; i < size; i++) {
            if (index >= list.size())
                return res;
            res.add(list.get(index));

            index += 1 + i * alpha;
        }
        return res;
    }
}

Related

  1. subList(List input, int startIndex, int count)
  2. subList(List it, int offset, int limit)
  3. sublist(List l, int fromIndex, int toIndex)
  4. subList(List list, int fromIndex, int toIndex)
  5. subList(List list, int fromIndex, int toIndex)
  6. subList(List list, int start, int end)
  7. sublist(List list, int start, int limit)
  8. subList(List list, int start, int max)
  9. subList(List list, int[] indexs)