Java - Slice any array at steps

本小妞迷上赌 提交于 2019-12-14 03:54:57

问题


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!


回答1:


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]




回答2:


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.




回答3:


Java has no built-in mechanism for this. You could write a helper function:

public static int[] sliceArray(int[] arr, int spacing) {
    int curr = 0;
    int[] newArr = new int[((arr.length - 1) / spacing) + 1];
    for (int i = 0; i < newArr.length; ++i) {
        newArr[i] = arr[curr];
        curr += spacing;
    }
    return newArr;
}

Example

Note that Michael's answer is better (or at least less verbose) if you can utilize Java 8.



来源:https://stackoverflow.com/questions/37929671/java-slice-any-array-at-steps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!