you mean by using a `(T) -> (R?)` and then `map...
# getting-started
r
you mean by using a
(T) -> (R?)
and then
mapNotNull
? That'd work (assuming
T : Any
) but it would create an intermediate list, which ideally I'd like to avoid.
e
If you’re worried about intermediate lists, you may want to try
.asSequence()
. Then you can just do:
Copy code
val sampleList = listOf(1, 2, 3)
val filterMappedList = sampleList.asSequence().filter { it > 1 }.map { it * 2 }.toList()
👍 1
💯 1
a
you mean by using a
(T) -> (R?)
and then
mapNotNull
?
No, I think Karel meant:
Copy code
inline fun <T, R : Any> List<T>.collect(
        predicate: (T) -> Boolean,
        transform: (T) -> R
): List<R> {
    return mapNotNull {
        if (predicate(it)) {
            transform(it)
        } else {
            null
        }
    }
}
k
Yes @arekolek, that's what I meant, thanks! I usually do something like that but in-place of course.
👍 1