81

I have a String[] that has at least 2 elements.

I want to create a new String[] that has elements 1 through the rest of them. So.. basically, just skipping the first one.

Can this be done in one line? easily?

3 Answers 3

140

Use copyOfRange, available since Java 1.6:

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

Alternatives include:

Sign up to request clarification or add additional context in comments.

4 Comments

The end index is exclusive
Wait, so does that mean I need a +1 to the .length?
No, because arrays are 0 based. Half open ranges and 0 based indexing work together nicely like that.
Sorry java-folks, but, coming from python code this looks just absurd
24
String[] subset = Arrays.copyOfRange(originalArray, 1, originalArray.length);

See Also:

Comments

7

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.

1 Comment

@AndreaBergonzo unfortunately, they provided methods for String[], int[], long[], double[] but not for byte[] :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.