Java - 按步骤对任何数组进行切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37929671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:57:31  来源:igfitidea点击:

Java - Slice any array at steps

javaarraysarraylistslice

提问by robman

In python we are able to do the following:

在python中,我们能够执行以下操作:

 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!

在 Java 中有与此等效的吗?我一直在寻找这种类型的数组切片,但我没有运气。任何帮助都会很棒,谢谢!

回答by Michael Markidis

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

如果您使用的是 Java 8,那么您可以使用流并执行以下操作:

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]

输出:[0, 3, 6, 9]

回答by gbtimmon

There is a method in Arrays that might help.

Arrays 中有一种方法可能会有所帮助。

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

It is obviously far less powerful the the python implementation.

显然,python 实现的功能要弱得多。

回答by Ironcache

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

Java 没有为此提供内置机制。你可以写一个辅助函数:

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.

请注意,如果您可以使用 Java 8,Michael 的回答会更好(或至少不那么冗长)。