Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remapping an Array in Java 8 Using Math and Streams

Apache commons math has a RealVector interface support a mapToSelf fluid interface that works like this:

 RealVector result = v.mapAddToSelf(3.4).mapToSelf(new Tan()).mapToSelf(new Power(2.3));

If I had a double[] array how would I do something similar with Java 8 streams and Java Math? The same array has to be reused.

TIA, Ole

like image 652
Ole Avatar asked Aug 29 '26 12:08

Ole


1 Answers

If you already have an array and you want to modify it in place, you can use Arrays.setAll:

Arrays.setAll(arr, i -> Math.pow(Math.tan(arr[i] + 3.4), 2.3));

And just in case you don't want to modify the original array, you can create a DoubleStream from it and map each element:

double[] res = 
    DoubleStream.of(arr).map(d -> Math.pow(Math.tan(d + 3.4), 2.3)).toArray();
like image 193
Alexis C. Avatar answered Aug 31 '26 01:08

Alexis C.