Reputation: 1514
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 ?
Upvotes: 0
Views: 85
Reputation: 1832
Try this:
String nameByCode = getProductList().stream()
.filter(Objects::nonNull) // filters null values in the list
.filter(it -> codeToFind.equals(it.code))
.findFirst() // returns java.util.Optional wrapper
.map(it -> it.getName()) // null-safe operation on the wrapper
.orElse(""); // fallback value
Links:
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#nonNull-java.lang.Object-
Upvotes: 3