NullVoxPopuli
NullVoxPopuli

Reputation: 65173

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

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?

Upvotes: 81

Views: 109633

Answers (3)

Bozho
Bozho

Reputation: 597224

Use copyOfRange, available since Java 1.6:

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

Alternatives include:

Upvotes: 140

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13803

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.

Upvotes: 7

Mark Peters
Mark Peters

Reputation: 81104

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

See Also:

Upvotes: 24

Related Questions