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.
Answer: Just use the Java addition operator, the plus sign ( + ), to add two integers together.
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.
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.
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]
You can simply concatenate primitive(int
) streams using IntStream.concat
as:
int[] m = IntStream.concat(IntStream.of(c), IntStream.of(d)).toArray();
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With