简体   繁体   English

如何使用 Java stream 克隆数组?

[英]How to clone an array using Java stream?

I have the following array:我有以下数组:

int nums[] = new int[]{1,2,3,4,5};

I want to add the same elements to the array using stream or another proper way if it is better using stream. There is addAll() method for List , but I could not use it for array and I am not sure if there is a proper way for array.我想使用 stream 或其他正确的方法将相同的元素添加到数组中,如果使用 stream 更好的话ListaddAll()方法,但我不能将它用于数组,我不确定是否有正确的方法阵列的方式。 So, how can I convert this list to:那么,如何将此列表转换为:

int nums[] = new int[]{1,2,3,4,5,1,2,3,4,5};

Based desired output, i'll make a guess that initial array is:基于所需的 output,我将猜测初始数组是:

int[] nums = new int[]{1, 2, 3, 4, 5};

You can't change the size of an array, once created, so you need to declare a new one.数组的大小一旦创建就无法更改,因此您需要声明一个新数组。 @Dan has already offered a solution with streams, so i'll give one with loops for completeness sake. @Dan 已经提供了一个带有流的解决方案,所以为了完整起见,我将给出一个带有循环的解决方案。

public class Temp {

    public static void main(String[] args) throws Exception {
        int[] nums = new int[]{1, 2, 3, 4, 5};
        System.out.println("Initial array");
        System.out.println(Arrays.toString(nums));

        int[] result = new int[nums.length * 2];
        for (int i = 0; i < nums.length; i++) {
            result[i] = nums[i];
            result[i + nums.length] = nums[i];
        }

        System.out.println("Result array");
        System.out.println(Arrays.toString(result));
    }
}

The upside is the single iteration used to fill result array.好处是用于填充结果数组的单次迭代。

Edit: As per suggestion from @OleV.V.编辑:根据@OleV.V 的建议。 a solution using System.arraycopy() would look like this:使用System.arraycopy()的解决方案如下所示:

public class Temp {

    public static void main(String[] args) throws Exception {
        int[] nums = new int[]{1, 2, 3, 4, 5};

        int[] result = new int[nums.length * 2];
        System.arraycopy(nums, 0, result, 0, nums.length);
        System.arraycopy(nums, 0, result, nums.length, nums.length);
        
        System.out.println(Arrays.toString(result));
    }
}

The upside is that System.arraycopy() is highly optimised and efficient.好处是System.arraycopy()是高度优化和高效的。

Iterative or stream based solutions are unnecessarily complicated and slow.迭代或基于 stream 的解决方案不必要地复杂和缓慢。 Just use System.arraycopy :只需使用System.arraycopy

public class Test {
    public static void main(String[] args) {

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

        int[] aAndB = new int[a.length + b.length];
        System.arraycopy(a, 0, aAndB, 0, a.length);
        System.arraycopy(b, 0, aAndB, a.length, b.length);

        System.out.println(Arrays.toString(aAndB));
    }
}

System.arraycopy is highly optimised: Why is System.arraycopy native in Java? System.arraycopy高度优化: Why is System.arraycopy native in Java?

Basing on the output you've shown int nums[] = new int[]{1,2,3,4,5,1,2,3,4,5};基于 output 你已经展示了int nums[] = new int[]{1,2,3,4,5,1,2,3,4,5}; and your statement和你的声明

I want to add the same elements to the array我想将相同的元素添加到数组中

I think what you were trying to ask was how to re-add the elements of an array to the same array, although your first snippet showed int nums[] = new int[]{4,5,6,7,0,1,2};我想你想问的是如何将数组的元素重新添加到同一个数组,尽管你的第一个片段显示int nums[] = new int[]{4,5,6,7,0,1,2}; while the output was totally unrelated to the first array (might have been a small blunder).而 output 与第一个数组完全无关(可能是一个小错误)。

However, in Java it is not possible to update the size of an array.但是,在 Java 中,无法更新数组的大小。 Once an array has been instantiated its size is fixed.一旦数组被实例化,它的大小就固定了。 What you can do is to declare another array with double the size of the original array you want to copy from.您可以做的是声明另一个数组,其大小是您要从中复制的原始数组的两倍。

As it has been pointed out in the comments by @Ole VV you could achieve this with IntStream , which is a better approach than the one I've used since it doesn't force you to change your working type from int[] to Integer[] .正如@Ole VV 在评论中指出的那样,您可以使用IntStream实现这一点,这是一种比我使用的方法更好的方法,因为它不会强制您将工作类型从int[]更改为Integer[] In fact, the Stream class works with generic types, so the only argument types it works with are references;事实上, Stream class 适用于泛型类型,因此它唯一适用的参数类型是引用; therefore you could only retrieve an array of Integer[] rather than int[] .因此,您只能检索Integer[]而不是int[]的数组。

Solution with IntStream使用 IntStream 的解决方案

int nums[] = new int[]{1, 2, 3, 4, 5};

int[] res = IntStream.concat(IntStream.of(nums), IntStream.of(nums)).toArray();

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

Solution with Stream解决方案 Stream

int nums[] = new int[]{1, 2, 3, 4, 5};

Integer[] res = new Integer[0];
res = Stream.concat(Arrays.stream(nums).boxed(), Arrays.stream(nums).boxed())
        .collect(Collectors.toList())
        .toArray(res);

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

how about using Arrays.copyOf(arg, arg) ?使用Arrays.copyOf(arg, arg)怎么样?

public static void main(String[] args) {
 int[] nums = new int[]{1, 2, 3, 4, 5, 1, 2, 3, 4, 5};
 int[] copiedArray = Arrays.copyOf(nums, nums.length);
}

If you really want to use Stream,如果你真的想用Stream,

public static void main(String[] args) {
 int[] nums = new int[]{1, 2, 3, 4, 5, 1, 2, 3, 4, 5};
 int[] copiedArray = Arrays.stream(nums).toArray();
}

use Arrays.asList(your array) to convert your array to list使用 Arrays.asList(your array) 将数组转换为列表

List<Integer> numList = Arrays.asList(nums);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM