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

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Use copyOfRange, available since Java 1.6:

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

Alternatives include:

Solution 2 - Java

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

See Also:

Solution 3 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullVoxPopuliView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaMark PetersView Answer on Stackoverflow
Solution 3 - JavaGrzegorz PiwowarekView Answer on Stackoverflow