Leyla
Leyla

Reputation: 23

Conditional max inside filter kotlin

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.

Upvotes: 2

Views: 982

Answers (2)

David Soroko
David Soroko

Reputation: 9086

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.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271040

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.

Upvotes: 3

Related Questions