Home > Software design >  Collect conditional items while streaming in kotlin
Collect conditional items while streaming in kotlin

Time:07-02

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)
                } // 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`.
}

CodePudding user response:

You can use .mapNotNull

val exceptionResults = listOf<String>("Name1", "Name2", "Name3")
.filter {
    it.length > 2
}
.mapNotNull { name ->
    try {
        if (name == "Name2") {
            throw Exception(name)
        } 
        null
    } catch (exception: Exception) {
        name
    }
}
println(exceptionRequests) // This prints `Name2`.

If exception isn't thrown, try catch expression will result in null. If exception is thrown, try catch expression will result in name. mapNotNull will filter out nulls (cases where exception wasn't thrown).

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"
}
  • Related