How can I combine two floating point arrays in Java?

Using Java 8 I am trying to combine two floating point arrays:

void f(float[] first, float[] second) {
    float[] both = ???
}

From a quick SO search, I thought I could just follow the instructions here . So I tried:

float both[] = FloatStream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();

But this does not compile as described here . So I tried a less efficient solution and directly used Stream:

float[] both = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(float[]::new);

It does not 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 easiest) way to concatenate two arrays float[]in Java 8?


Update: Obviously, the whole point of the question is what I have to deal with float, not double.

+4
source share
4 answers

, System.arrayCopy(), . , .

+8

FloatStream, () float , , ,

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;
}

. , .

+2

. . Apache Commons ArrayUtils.

float[] both = ArrayUtils.addAll(first, second);

Under the covers, it has some logic for several special cases when one input or the other is null, followed by two calls System.arraycopy. But you don’t have to worry about anything.

+1
source

is there a guava option? since he has a Floats.concatlittle more freely, but he is still System.arrayCopyfrom below.

The problem is that it jdkdoes not have FloatStream- which you can use here, you can return Float[]from such a thing:

Stream.concat(
            IntStream.range(0, first.length)
                    .boxed()
                    .map(x -> first[x]),
            IntStream.range(0, first.length)
                    .boxed()
                    .map(y -> first[y]))
            .toArray(Float[]::new);

But this is too many operations for such a simple thing.

0
source

Source: https://habr.com/ru/post/1688131/


All Articles