Java List Slice slice(List list, Integer start, Integer stop)

Here you can find the source of slice(List list, Integer start, Integer stop)

Description

Slices a list, Python style

License

Open Source License

Parameter

Parameter Description
list the list
start the start index (null means the beginning of the list)
stop the stop index (null means the end of the list)

Return

the slice

Declaration

public static <T> List<T> slice(List<T> list, Integer start, Integer stop) 

Method Source Code

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

import java.util.*;

public class Main {
    /**/*from w ww  .  ja  v  a2 s. c  o m*/
     * Slices a list, Python style
     * @param list the list
     * @param start the start index (null means the beginning of the list)
     * @param stop the stop index (null means the end of the list)
     * @return the slice
     */
    public static <T> List<T> slice(List<T> list, Integer start, Integer stop) {
        int size = list.size();

        if (start == null) {
            start = 0;
        } else if (start < 0) {
            start = size + start;
        }

        if (stop == null) {
            stop = size;
        } else if (stop < 0) {
            stop = size + stop;
        }

        if (start >= size || stop <= 0 || start >= stop) {
            return Collections.emptyList();
        }

        start = Math.max(0, start);
        stop = Math.min(size, stop);

        return list.subList(start, stop);
    }
}

Related

  1. slice(List as, int start, int end)
  2. slice(List c, int fromIndex, int toIndex)
  3. slice(List list, int index, int count)
  4. slice(List list, int start, int end)
  5. sliceList(final List list, final long offset, final int limit)
  6. sliceListByIndices(final List indices, final List list)
  7. slices(List list, int step)