How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:
methodName(object array, int start, int
JDK >= 1.8
I agree with all the answers above. There is also a nice way with Java 8 Streams:
int[] subArr = IntStream.range(startInclusive, endExclusive)
.map(i -> src[i])
.toArray();
The benefit about this is, it can be useful for many different types of "src" array and helps to improve writing pipeline operations on the stream.
Not particular about this question, but for example, if the source array was double[] and we wanted to take average() of the sub-array:
double avg = IntStream.range(startInclusive, endExclusive)
.mapToDouble(index -> src[index])
.average()
.getAsDouble();