Ivan Alex
Ivan Alex

Reputation: 95

Java take range from array

Does Java have a method of Array drop?
In Scala we have: Array.drop(10).take(16) or maybe to take a range of members of an array?
In Java I can only do array[10] for example.

Upvotes: 1

Views: 214

Answers (2)

Marv
Marv

Reputation: 3557

There is Arrays::copyOfRange:

It has three parameters:

  • original: the source array
  • from: the starting index, inclusive
  • to: the end index, exclusive

Not that it returns a new array, meaning that if you change the values of the resulting array, the original array does not change.

The method is overloaded to work for all primitive types and for objects.

Here's an example use:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        final int[] source = IntStream.range(0, 10).toArray()
        System.out.println(Arrays.toString(source));

        final int[] result = Arrays.copyOfRange(source, 3, 8);
        System.out.println(Arrays.toString(result));
    }
}

Which prints:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]

For more information, see the docs

Upvotes: 2

Mureinik
Mureinik

Reputation: 311798

I think it's easiest to achieve such semantics by streaming the array:

SomeClass[] sourceArray = /* something */;

SomeClass[] result = 
    Arrays.stream(sourceArray).skip(10L).limit(16L).toArray(SomeClass[]::new);

Upvotes: 1

Related Questions