Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda