[英]Java: is there an easy way to select a subset of an array?
I have a String[]
that has at least 2 elements.我有一个至少有 2 个元素的
String[]
。
I want to create a new String[]
that has elements 1 through the rest of them.我想创建一个新的
String[]
,其中包含元素 1 到其余元素。 So.. basically, just skipping the first one.所以..基本上,只是跳过第一个。
Can this be done in one line?这可以在一行中完成吗? easily?
容易吗?
Use copyOfRange
, available since Java 1.6:使用从 Java 1.6 开始可用的
copyOfRange
:
Arrays.copyOfRange(array, 1, array.length);
Alternatives include:替代方案包括:
ArrayUtils.subarray(array, 1, array.length)
from Apache commons-langArrayUtils.subarray(array, 1, array.length)
System.arraycopy(...)
- rather unfriendly with the long param list. System.arraycopy(...)
- 对长参数列表相当不友好。String[] subset = Arrays.copyOfRange(originalArray, 1, originalArray.length);
See Also:另见:
Stream API could be used too:也可以使用 Stream API:
String[] array = {"A", "B"};
Arrays.stream(array).skip(1).toArray(String[]::new);
However, the answer from Bozho should be preferred.但是,应该首选Bozho的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.