Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two int[]

There are easy solutions for concatenating two String[] or Integer[] in java by Streams. Since int[] is frequently used. Is there any straightforward way for concatenating two int[]?

Here is my thought:

int[] c = {1, 34};
int[] d = {3, 1, 5};
Integer[] cc = IntStream.of(c).boxed().toArray(Integer[]::new);
Integer[] dd = Arrays.stream(d).boxed().toArray(Integer[]::new);
int[] m = Stream.concat(Stream.of(cc), Stream.of(dd)).mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(m));

>>
[1, 34, 3, 1, 5]

It works, but it actually converts int[] to Integer[], then converts Integer[] back to int[] again.

like image 975
Simon Z. Avatar asked Feb 25 '19 10:02

Simon Z.


People also ask

How do I combine two ints in Java?

Answer: Just use the Java addition operator, the plus sign ( + ), to add two integers together.

How do you concatenate int in Python?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

How do I concatenate an int to a string in Java?

Java For Testers To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.


3 Answers

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]

like image 104
Ravindra Ranwala Avatar answered Oct 13 '22 13:10

Ravindra Ranwala


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

int[] m = IntStream.concat(IntStream.of(c), IntStream.of(d)).toArray();
like image 35
Naman Avatar answered Oct 13 '22 13:10

Naman


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++;
}
like image 2
the gamer cat Avatar answered Oct 13 '22 13:10

the gamer cat