Using two streams in Java lambda to compute covariance

后端 未结 2 410
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 21:47

Let\'s say I have two arrays of double. I\'ve been experimenting with Stream from Java 8. I think I\'ve understood the main ideas but then I realised that I\'m not sure how

2条回答
  •  天命终不由人
    2021-01-15 22:27

    Other FP languages have the zip operation, which makes a stream of pairs from two streams of elements. This has not been made available in Java.

    In case of arrays, however, you can easily make a stream of array indices and let your functions close over the arrays, accessing them by the index parameter.

    I should also warn you that in this line

    .mapToDouble(d -> d.doubleValue() - mean(xs))
    

    you are making your program complexity O(n2) because mean is recalculated at each step. You should precalculate that and close over the result in the lambda.

提交回复
热议问题