开发者

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 开发者_C百科the rest of them. So.. basically, just skipping the first one.

Can this be done in one line? easily?


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.


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

See Also:

  • java.util.Arrays


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜