toCollection
Appends this Optional's value to the given destination collection if present.
Since Kotlin
1.8Samples
import java.util.Optional
import kotlin.jvm.optionals.*
fun main() {
//sampleStart
val maybeItsAnAnimal = Optional.of("Anonymous Capybara")
val maybeItsAnAnimalAsWell = Optional.empty<String>()
val animals = arrayListOf("Hilarious Honey Badger")
// Add to the collection if present
maybeItsAnAnimal.toCollection(animals)
maybeItsAnAnimalAsWell.toCollection(animals)
println(animals) // [Hilarious Honey Badger, Anonymous Capybara]
//sampleEnd
}