java – 将特定索引处的数组值复制到另一个数组

我遇到了一种情况,我有一个数组,我需要将一些特定属性(即特定indinces的值)复制到另一个数组而不是整个数组.

例如,如果初始数组是:

double[] initArray = {1.0, 2.0, 1.5, 5.0, 4.5};

那么如果我只想复制第2,第4和第5属性(即这些索引处的值),那么所需的输出数组将是:

double[] reducedArray = {2.0, 5.0, 4.5};

我知道如果指数以顺序形式出现,例如1-3然后我可以使用System.arraycopy(),但我的索引没有那个方面.

那么,有没有任何官方的方法来做到这一点,除了通过每个值的琐碎循环并复制所需的:

double[] includedAttributes = {1, 4, 5};
double[] reducedArray = new double[includedAttributes.length];
for(int j = 0; j < includedAttributes.length; j++) {
    reducedArray[j] = initArray[includedAttributes[j]];
}

最佳答案 使用流,它是一个单行.

鉴于:

int[] indices;
double[] source;

然后:

double[] result = Arrays.stream(indices).mapToDouble(i -> source[i]).toArray();
点赞