Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - best way converting array elements

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 ?

like image 327
ic3 Avatar asked Aug 14 '15 07:08

ic3


2 Answers

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.

like image 159
Tagir Valeev Avatar answered Oct 03 '22 08:10

Tagir Valeev


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.

like image 44
Stuart Marks Avatar answered Oct 03 '22 06:10

Stuart Marks