Java List Range getRange(List list, int start, int count)

Here you can find the source of getRange(List list, int start, int count)

Description

Get a range from a list based on start and count parameters in a safe way.

License

Open Source License

Parameter

Parameter Description
T element
list The List
start The start index
count The number of elements to add

Return

The sublist consisting at most of count elements (less if the parameters exceed the size of the list)

Declaration

public static <T> List<T> getRange(List<T> list, int start, int count) 

Method Source Code


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

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*www .j  a  v a  2  s.c o  m*/
     * Get a range from a list based on start and count parameters in a safe way.
     *
     * @param <T> element
     * @param list The List
     * @param start The start index
     * @param count The number of elements to add
     *
     * @return The sublist consisting at most of {@code count} elements (less if the parameters
     * exceed the size of the list)
     */
    public static <T> List<T> getRange(List<T> list, int start, int count) {
        if (start >= list.size() || count <= 0) {
            return new ArrayList<>();
        } else if (start < 0) {
            start = 0;
        }
        int end = Math.min(list.size(), start + count);
        return list.subList(start, end);
    }

    /**
     * Get all elements from a list starting from the given index.
     *
     * @param <T> element
     * @param list The List
     * @param start The start index
     *
     * @return The sublist of all elements from index {@code start} and on; empty list
     * if the start index exceeds the list's size
     */
    public static <T> List<T> getRange(List<T> list, int start) {
        if (start >= list.size()) {
            return new ArrayList<>();
        }
        return getRange(list, start, list.size() - start);
    }
}

Related

  1. getRange(List numbers)
  2. getRange(List list, int start)