Using Java 8 I am trying to concatenate two float arrays:
void f(float[] first, float[] second) {
float[] both = ???
}
From a quick SO search, I thought I could simply follow instruction from here. So I tried:
float both[] = FloatStream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();
But this does not compile as explained here. So I tried the less efficient solution and use a Stream
directly:
float[] both = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(float[]::new);
It fails to compile from my eclipse saying:
The method stream(T[]) in the type Arrays is not applicable for the arguments (float[])
What is the most efficient (and simple) way of concatenating two float[]
arrays in Java 8 ?
Update: obviously the whole point of the question is that I have to deal with float
and not double
.
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
addAll() method to concatenate two arrays into one. This method works for both primitive as well as generic type arrays.
Don't do it yourself, use System.arrayCopy()
to copy both arrays into a new array of the combined size. That's much more efficient, as it uses native OS code.
Since there is no FloatStream
and even creating an (inefficient) boxed stream out of a float array is not simple, you won’t find a stream based solution that is simpler than
static float[] f(float[] first, float[] second) {
float[] both = Arrays.copyOf(first, first.length+second.length);
System.arraycopy(second, 0, both, first.length, second.length);
return both;
}
Even the option to use a parallel stream is unlikely to outweigh the raised complexity. You would need really large arrays to see a benefit.
Don't write your own code to do this. The problem has already been solved and tested. You should use the Apache Commons ArrayUtils
class.
float[] both = ArrayUtils.addAll(first, second);
Under the covers, it has some logic for a couple of special cases where one input or the other is null, followed by two calls to System.arraycopy
. But you don't need to worry about any of that.
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