Reputation: 65173
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
Reputation: 597224
Use copyOfRange
, available since Java 1.6:
Arrays.copyOfRange(array, 1, array.length);
Alternatives include:
ArrayUtils.subarray(array, 1, array.length)
from Apache commons-langSystem.arraycopy(...)
- rather unfriendly with the long param list.Upvotes: 140
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
Reputation: 81104
String[] subset = Arrays.copyOfRange(originalArray, 1, originalArray.length);
See Also:
Upvotes: 24