How to ensure min() operation on collection return a default value incase of null r

Hi all,

I was wondering how to write equivalent of min().orElse(0) of java collection in kotlin.

This is my attempt

val minList:List<String> = listOf("1", "2")
val min:Long = minList.map { x->x.toLong() }.min()?.toLong()?:0;

I was wondering whether there would be any better approach?

Looks ok, you don’t need the second .toLong:

val min = minList.map { x -> x.toLong() }.min() ?: 0;
1 Like

Thanks

You could also use

val min = minList.minBy { it.toLong() }.toLong() ?: 0

However I would prefer your version if you are interested in the long value. If you care about the string, minBy is what you want.

If it’s a Java collection containing nulls, the type would be List<String?> so just min() wouldn’t work and you’d need val min = list.minBy { x -> x?.toLong() ?: 0 }

This still returns null for empty lists.