How to safely filter elements in collection?

Viewed 48

I have data class Product:

data class Product(
    val name: String,
    val code: String?
)

And I need to get product name from product list by given code. Here is my code in Kotlin:

 val productList = getProductList()
    val codeToFind = "1234"

    val nameByCode = productList.firstOrNull { it.code == codeToFind }
        ?.name ?: ""

Is it possible to write the same concise and safe code in the Java using Stream API ?

1 Answers
Related