Java: Examples of the Java list/array `subList` method (list subset)

As a little note today, if you ever need to extract a subset of a Java list or array, here are some examples of the Java subList method:

import java.util.*;

public class SubList {

    public static void main(String[] args) {

        List<String> x = new ArrayList<>();

        // `subList(int fromIndex, int toIndex)`
        // array indexes start at 0.
        // 1st arg is inclusive (included), 2nd arg is exclusive (not included).
        List a = x.subList(0,1);  // [a]
        List b = x.subList(0,2);  // [a, b]
        List c = x.subList(0,4);  // [a, b, c, d]      # same as `x.subList(0,x.size()-1)`
        List d = x.subList(0,5);  // [a, b, c, d, e]   # same as `x.subList(0,x.size())`
        List e = x.subList(0,6);  // IndexOutOfBoundsException
        List f = x.subList(1,1);  // f []
        List g = x.subList(1,2);  // g [b]
        List h = x.subList(2,5);  // h [c, d, e]

If you print the results of each line you’ll see the results on the right side of the comments. As shown:

  • The first element in a list or array is at index 0
  • The toIndex is exclusive, meaning it won’t be included in the results
  • If you go outside the size of the initial list, you’ll get an IndexOutOfBoundsException
  • The original list isn’t modified; if you print x, you’ll see that it still includes all of the original elements

If you ever need to extract a subset of a Java list or array into another list or array, I hope these Java subList examples are helpful.