Home > database >  Conditional max inside filter kotlin
Conditional max inside filter kotlin

Time:10-23

I have a list, each element with the following fields: active: true/false, optional_id: Int?, name: String

I am filtering for fields that have active true, to get the highest optional_id.

      testList.filter { it.active == true }
            .maxByOrNull { it.optional_id }
            ?. optional_id ?: 0

The idea is, if there are objects in the list, with the field active true, to get the highest optional_id amongst those. Else, if they are all false (no active field), then return 0. But since optional_id is of type Int?, maxByOrNull does not accept it without asserting !!. Is there any other way to handle null assertions for this scenario ? I can't change the type of optional_id.

CodePudding user response:

You can use maxOfWithOrNull with a nullsFirst comparator.

val highestOptionalId = testList.filter { it.active == true }
    .maxOfWithOrNull(nullsFirst(naturalOrder())) { it.optionalId }
    ?: 0

"Of" suggests that it returns the selector's value, rather than the object in the list. "With" suggests that it uses a Comparator.

CodePudding user response:

You could do the following (use Java MIN_VALUE for Integer as the fallback for null values):

list2.filter { it.active }
    .maxByOrNull { it.optional_id ?: MIN_VALUE }
    ?. optional_id ?: 0

CodePudding user response:

Is this what you are looking for?

testList.filter { it.active && it.optional_id != null }
    .maxByOrNull { it.optional_id!! } ?.optional_id 
    ?: 0

Following filter(...) you can safely assume (looks like you have no concurrency concerns) that optional_id is not null in maxByOrNull.

  • Related