Get Subarray of an Array between Specified Indexes in Java

In this post, we will discuss several methods to get subarray of a non-primitive array between specified indices.


 

1. Arrays.copyOfRange()

The standard way to get subarray of an array is to use the Arrays.copyOfRange() which returns a subarray containing the specified range from the original array as shown below.

 

Download   Run Code

Output:

[B, C, D, E]

 

2. Java 8

We can use the Java Streams API, introduced in Java SE 8, to get a subarray from an array. The idea is to get a Stream of elements between the specified range and then call toArray() method to accumulate elements of the stream into a new array.

 

Download   Run Code

Output:

[B, C, D, E]

 

3. System.arraycopy()

System.arraycopy() method can also be used to get a copy from the specified position in the source array to the specified position of the destination array.

 

Download   Run Code

Output:

[B, C, D, E]

 

4. Array -> List -> SubList -> SubArray

The idea here is to convert the array into a List and use subList() method to get elements between the desired range. Then, we use toArray(T[]) method to copy the list into a newly allocated array.

Please note that this method doesn’t actually copy the array. Both the resultant list and the sublist are backed by the original array and just references the array.

 

Download   Run Code

Output:

[B, C, D, E]

 

5. Custom method

We can also write our own custom method which simply copies the desired elements from original array into the new array.

 

Download   Run Code

Output:

[B, C, D, E]

 

6. ArrayUtils.subarray() in Apache Commons

Apache Commons ArrayUtils class provides subarray() method that returns an Object sub-array containing the elements between specified indices. See how to convert an object array to Integer array.

 

Download

Output:

[B, C, D, E]

 

7. Arrays.copyOf()

Finally Arrays.copyOf() can also be used to copy the specified array to an array of specified type. But this approach won’t work if sub-array starts at some intermediate index, rather than the first index.

 

Download   Run Code

Output:

[A, B, C, D, E]

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz