Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!