在Kotlin代码中,我有一个对象列表,当通过filter
和map
处理它时,我想收集特别感兴趣的项目.抛弃其他人.
例如,我使用foreach
循环,如下所示.用map
而不是foreach
能让它变得更好吗?
fun main() {
val exceptionRequests = mutableListOf<String>()
listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2
}
.forEach {
try {
if (it == "Name2") {
throw Exception(it)
} // Throwing exception here like this for simplicity. In real case, business logic throws exception.
} catch (exception: Exception) {
exceptionRequests.add(it)
}
}
println(exceptionRequests) // This prints `Name2`.
}