Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Slice any array at steps

In python we are able to do the following:

 array = [0,1,2,3,4,5,6,7,8,9,10]
 new_array= array[::3]
 print(new_array)
>>>[0,3,6,9]

Is there an equivalent to this in Java? I have been looking for this type of array slicing, but I have had no luck. Any help would be great, Thanks!

like image 898
robman Avatar asked Feb 07 '23 17:02

robman


2 Answers

If you are using Java 8, then you can make use of streams and do the following:

int [] a = new int [] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// filter out all indices that evenly divide 3
int [] sliceArr = IntStream.range(0, a.length).filter(i -> i % 3 == 0)
    .map(i -> a[i]).toArray();

System.out.println(Arrays.toString(sliceArr));

Outputs: [0, 3, 6, 9]

like image 178
Michael Markidis Avatar answered Feb 19 '23 19:02

Michael Markidis


There is a method in Arrays that might help.

 int[] newArr = Arrays.copyOfRange(arr, 5,10); 

It is obviously far less powerful the the python implementation.

like image 27
gbtimmon Avatar answered Feb 19 '23 20:02

gbtimmon