-1

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. So, how can I convert this list to:

int nums[] = new int[]{1,2,3,4,5,1,2,3,4,5};
  • 2
    The array has a fixed size. We cannot increase or decrease the size of the array at runtime. – Sibin Rasiya May 22 '22 at 08:15
  • What about copy and transform to another array? –  May 22 '22 at 08:16
  • 5
    I find your example confusing. You say you want to add the same elements to the array, but some elements of initial array(0, 6, 7) are missing from result, and result has additional elements(3). – Chaosfire May 22 '22 at 08:19
  • 4
    I don't understand the correlation between the first array shown and the second. Do you want to add the elements of the first array into a new one? Basically @Chaosfire wrote the exact same thing when I was typing my comment. I'm having his same issue in understanding your code. – Dan May 22 '22 at 08:20
  • I apologize all of you who try to help. I fixed but anyhow it could not be saved and the elements in the array was still wrong. Now I fixed and thanks all of you for helps. –  May 23 '22 at 06:06

5 Answers5

3

Based desired output, i'll make a guess that initial array is:

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.

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. a solution using System.arraycopy() would look like this:

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.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • 1
    @OleV.V. Solution with `System.arraycopy()` is quite easy, i'll add one in a minute. The thing is, honestly, i am not aware of how this method works under the hood. It seems to me, that using it means iterating twice trough initial array to fill up the resulting array. Might be totally wrong, please feel free to correct me. The only upside of current solution is that it fills up the result using single iteration over initial array. – Chaosfire May 22 '22 at 09:36
  • 2
    Or `int[] result = Arrays.copyOf(nums, nums.length * 2); System.arraycopy(nums, 0, result, nums.length, nums.length);` See [`Arrays.copyOf(int[] original, int newLength)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#copyOf(int%5B%5D,int)). Yes, that’s “two iterations”, but given how low level copying operations and CPU caches work, it’s not slower than your loop. It might be even faster. – Holger May 23 '22 at 10:45
3

Iterative or stream based solutions are unnecessarily complicated and slow. Just use 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?

tgdavies
  • 10,307
  • 4
  • 35
  • 40
2

Basing on the output you've shown 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}; while the output was totally unrelated to the first array (might have been a small blunder).

However, in Java it is not possible to update the size of an array. 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 V.V. 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[]. In fact, the Stream class works with generic types, so the only argument types it works with are references; therefore you could only retrieve an array of Integer[] rather than int[].

Solution with 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

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));
Dan
  • 3,647
  • 5
  • 20
  • 26
  • good call. So focused in using `Stream` that I haven't thought about using `IntStream`. I'll improve my answer. Thanks. – Dan May 22 '22 at 08:50
  • 1
    It’s a blurred world where we got `IntStream` and `DoubleStrem` but neither `FloatStream` nor `CharStream`. I often need to look through the documentation to establish what is doable and what isn’t. – Ole V.V. May 22 '22 at 08:52
  • Yeah I agree with you. They offered primitive implementations of the streams but only for certain types for some reasons – Dan May 22 '22 at 08:56
1

how about using 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,

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();
}
Asgar
  • 1,920
  • 2
  • 8
  • 17
-3

use Arrays.asList(your array) to convert your array to list

List<Integer> numList = Arrays.asList(nums);
YaziD
  • 57
  • 9