Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ParallelStream toArray of higher size Java8

I am trying to create an array with higher size from a parallel stream

myList.parallelStream().map((listElm) -> {
            return someObjectMorpher(listElm);}).toArray(size -> new SomeObject[size+4]);
  1. Is it guaranteed that the last 4 elements of the array will always be null? Which means toArray will always populate at first indices of the Array.

  2. Is there a possibility of having toArray populate an already created array

    SomeObjet [] arr = new SomeObject[myList.size() + 4];
    arr[0] = new SomeObject(x);
    myList.parallelStream()
        .map((listElm) -> { return someObjectMorpher(listElm);})
        .toArray(**///use arr** );
    
like image 294
user3813133 Avatar asked Apr 01 '26 23:04

user3813133


1 Answers

Is it guaranteed that the last 4 elements of the array will always be null?

Essentially, no. The last four elements of the array will retain their previous value. If the value happened to be null, then they will remain null. For example:

Integer[] array = Stream.of(7, 8).parallel().toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});

System.out.println(Arrays.toString(array));

Output:

[7, 8, 3, 4, 5, 6]

Is there a possibility of having toArray populate an already created array

Yes, see above, as well as another example:

Integer[] array = new Integer[] {1, 2, 3, 4, 5, 6};

Integer[] newArray = Stream.of(7, 8).parallel().toArray(i -> array);

System.out.println(Arrays.toString(newArray));

Output:

[7, 8, 3, 4, 5, 6]

Note: Attempting this with sequential streams will throw an IllegalStateException if the length of the array differs from the size of the stream.

like image 128
Jacob G. Avatar answered Apr 03 '26 17:04

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!