Lilja
04/02/2018, 10:16 AMnull
, 1
, 2
and so on. It's named condition
. I have a list, listOf(1,2,3,4)
. That's named stream
. Based of on condition
I would like to filter
for stream
, but only if it's non-null
. How can I perform a filter
operation if a condition either is null
or a value? if(condition != null) stream.filter(it == condition) else stream
is one solution I suppose but is there a cleaner way?Andreas Sinz
04/02/2018, 11:06 AMif
-version is fine. If you want you can create your own little helper function:
inline fun <T> T.runIf(predicate: Boolean, f: (T) -> T) =
if (predicate)
f(this)
else
this
myList.runIf(condition != null) {
it.filter(it == condition)
}