Java: is there an easy way to select a subset of an array?

Solution 1:

Use copyOfRange, available since Java 1.6:

Arrays.copyOfRange(array, 1, array.length);

Alternatives include:

  • ArrayUtils.subarray(array, 1, array.length) from Apache commons-lang
  • System.arraycopy(...) - rather unfriendly with the long param list.

Solution 2:

String[] subset = Arrays.copyOfRange(originalArray, 1, originalArray.length);

See Also:

  • java.util.Arrays

Solution 3:

Stream API could be used too:

String[] array = {"A", "B"};

Arrays.stream(array).skip(1).toArray(String[]::new);

However, the answer from Bozho should be preferred.