In Kotlin code, I have a list of objects and while processing it via filter
and map
I want to collect items of particular interest. And discard others.
For example, I am using foreach
loop as below. Is it possible to make it better by using map
instead of foreach
?
fun main() {
val exceptionRequests = mutableListOf<String>()
listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2
}
.forEach {
try {
if (it == "Name2") {
throw Exception(it)
}
} catch (exception: Exception) {
exceptionRequests.add(it)
}
}
println(exceptionRequests) // This prints `Name2`.
}
CodePudding user response:
Why do you compare it and throw an Exception and then add that in the catch block?
You can derive exceptionRequests as follow:
val exceptionRequests = listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2 && it == "Name2"
}
CodePudding user response:
Perhaps I'm misunderstanding your question, but your current example can simply be written as
val exceptionRequests = listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2
}
.filter {
it == "Name2"
}
println(exceptionRequests) // This prints `Name2`.
(if you want to keep these filters separate - alternatively, you can combine them to a single filter)