Concatenating two int[]

后端 未结 3 884
野的像风
野的像风 2020-12-15 18:02

There are easy solutions for concatenating two String[] or Integer[] in java by Streams. Since int[] is frequently used.

相关标签:
3条回答
  • 2020-12-15 18:06

    You can use IntStream.concat in concert with Arrays.stream to get this thing done without any auto-boxing or unboxing. Here's how it looks.

    int[] result = IntStream.concat(Arrays.stream(c), Arrays.stream(d)).toArray();
    

    Note that Arrays.stream(c) returns an IntStream, which is then concatenated with the other IntStream before collected into an array.

    Here's the output.

    [1, 34, 3, 1, 5]

    0 讨论(0)
  • 2020-12-15 18:06

    You can simply concatenate primitive(int) streams using IntStream.concat as:

    int[] m = IntStream.concat(IntStream.of(c), IntStream.of(d)).toArray();
    
    0 讨论(0)
  • 2020-12-15 18:12

    Use for loops, to avoid using toArray().

    int[] e = new int[c.length+d.length];
    int eIndex = 0;
    for (int index = 0; index < c.length; index++){
        e[eIndex] = c[index];
        eIndex++;
    }
    for (int index = 0; index < d.length; index++){
        e[eIndex] = d[index];
        eIndex++;
    }
    
    0 讨论(0)
提交回复
热议问题