Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin and parallelStream toArray

I think I'm getting sidetracked. I'm trying to utilize the Java parallelStream for performance reasons.

A function Specimen.pick() samples and returns an instance of Specimen. I want to parallize this with parallelStream when replacing pool.

var pool: Array<Specimen> = Array(100_000) .. 

This is what I'm trying to write in Kotlin:

pool = pool.asList().parallelStream().map { Specimen.pick(pool, wheel, r.split()) }.toArray(Specimen::new)

Which errors out on ::new

Instead I have to juggle back and forth between list and array:

pool = pool.asList().parallelStream().map { Specimen.pick(pool, wheel, r.split()) }.collect(Collectors.toList()).toTypedArray()

Which works, but seems resource wasteful rather than going directly to Array. If I let IntelliJ try to Kotlinize a Java example of this:

Java:

Person[] men = people.stream()
                      .filter(p -> p.getGender() == MALE)
                      .toArray(Person[]::new);

IntelliJ transformation:

val men = people.stream()
            .filter({ p -> p.getGender() === MALE })
            .toArray(Person[]::new  /* Currently unsupported in Kotlin */)

So maybe this is coming for Kotlin? Or is there another better way?

like image 309
Peheje Avatar asked Jul 17 '26 00:07

Peheje


1 Answers

You can't use an array constructor reference, but every method reference can be expressed using a lambda expression:

.toArray<Person>({length -> arrayOfNulls(length)})
like image 200
JB Nizet Avatar answered Jul 19 '26 09:07

JB Nizet



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!