![]() |
VOOZH | about |
In Java, subarrays are the contiguous portion of an array. Extracting subarrays in Java is common when working with data that needs slicing or partitioning. Java does not have a direct method to create subarrays, we can extract subarrays using simple techniques like built-in methods or manual loops.
Example: The simplest way to get a subarray is by using a manual loop. This approach is straightforward and gives us full control over the array slicing.
2 3 4
Arrays.copyOfRange()TheArrays.copyOfRange() is the easiest and efficient method to get a subarray. It eliminates the need for a manual loop. It is useful when we want a quick and clean way to extract a subarray without need to think about index management.
[2, 3, 4]
In Java 8, Streams provide a modern, functional approach for extracting subarrays. This method is useful when additional processing is needed.
[2, 3, 4]
Explanation: The IntStream.range(from, to) generates a stream of indices. The .map(i -> array[i]) maps each index to the corresponding array element. The .toArray() method converts the stream back to an array.