How to get an ObservableFloatArray from a Stream?

前端 未结 2 1902
孤街浪徒
孤街浪徒 2020-12-06 19:14

This is nearly the same question as this one, but in the opposite direction.

I know there\'s no FloatStream in Java 8, and there\'re no many use cases f

2条回答
  •  醉梦人生
    2020-12-06 20:17

    Keep in mind that a Stream defines an operation rather that a storage. So for most operations, using a float provides only little benefit over double values when CPU registers are used. There might be a theoretical improvement for operations that could be accelerated using SSE or GPU, but that’s not relevant here.

    So you can use a DoubleStream for that operation, the only thing you need is a collector capable of collecting a DoubleStream into a float[] array:

    float[] arrayVertices = listVertices.stream()
        .flatMapToDouble(vertex->DoubleStream.of(vertex.x, vertex.y, vertex.z))
        .collect(FaCollector::new, FaCollector::add, FaCollector::join)
        .toArray();
    
    static class FaCollector {
        float[] curr=new float[64];
        int size;
        void add(double d) {
            if(curr.length==size) curr=Arrays.copyOf(curr, size*2);
            curr[size++]=(float)d;
        }
        void join(FaCollector other) {
            if(size+other.size > curr.length)
                curr=Arrays.copyOf(curr, size+other.size);
            System.arraycopy(other.curr, 0, curr, size, other.size);
            size+=other.size;
        }
        float[] toArray() {
            if(size!=curr.length) curr=Arrays.copyOf(curr, size);
            return curr;
        }
    }
    

    This supports parallel processing, however, for an operation that merely consist of data copying only, there is no benefit from parallel processing.

提交回复
热议问题