Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate two float arrays in Java?

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.

like image 631
malat Avatar asked Oct 25 '17 09:10

malat


People also ask

Can we concatenate two arrays in Java?

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.

What is the method used if you want to concatenate two arrays?

addAll() method to concatenate two arrays into one. This method works for both primitive as well as generic type arrays.


3 Answers

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.

like image 115
Sandip Solanki Avatar answered Oct 13 '22 18:10

Sandip Solanki


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.

like image 24
Holger Avatar answered Oct 13 '22 16:10

Holger


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.

like image 1
Dawood ibn Kareem Avatar answered Oct 13 '22 16:10

Dawood ibn Kareem