Starting with Java 8 so need a bit of time to get used to it. It's a classical problem, I've an array of objects that I want to transform.
Before Java8 the ideal code would be (no null pointers):
P[] outputArray = new P[inputArray.length];
for (int i =0; i< inputArray.length; i++ )
{
outputArray [i] = inputArray[i].transformToP();
}
What is the best version in Java8 ?
Using the Stream API it's quite simple:
P[] outputArray = Arrays.stream(inputArray).map(e -> e.transformToP()).toArray(P[]::new);
Also method reference can be used (suppose that I
is the type of input elements):
P[] outputArray = Arrays.stream(inputArray).map(I::transformToP).toArray(P[]::new);
Note that you may have problems if transformToP()
method throws checked exceptions. In this case convert them to unchecked ones or consult this question.
Using a stream over an array is a fine technique as described in Tagir Valeev's answer. However, don't forget about Arrays.setAll
. This is a handy shortcut for setting all the elements of an array based on index. To transform an array to a new array by some function, you could do this:
P[] outputArray = new P[inputArray.length];
Arrays.setAll(outputArray, i -> inputArray[i].transform());
You don't have to copy it into a new array. If you want to transform the array in-place, you could do this:
Arrays.setAll(array, i -> array[i].transform());
There is also a parallel variation parallelSetAll
.
Under the covers this is just an IntStream.range
over the indexes of the input array, but it's sometimes darned convenient for quick one-liners.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With