Using the filter method with Kotlin

Asked

Viewed 32 times

0

I have the class Posicao and in it I have an attribute data: LocalDate.

I have an Array of FaixaPreco which contains 12 objects, 1 for each month of the year.

Based on the position date, I wanted to retrieve the FaixaPreco which fits:

It may be so, dataPosicao >= dataInicial of range.

data class Posicao(
    val id: Long? = null,
    var data: LocalDate? = null,
    var nome: String? = null
)
data class FaixaPreco(
    val id: Long? = null,
    var dataInicial: LocalDate,
    var taxaAa: BigDecimal? = null
)
val posicao = Posicao(1L, LocalDate.of(2021, 1, 13), "posição")
    
    
val faixas: MutableList<FaixaPreco> = mutableListOf();
faixas.add(FaixaPreco(1L, LocalDate.of(2021, 1, 12), BigDecimal("0.01")))
faixas.add(FaixaPreco(2L, LocalDate.of(2021, 2, 12), BigDecimal("0.03")))
faixas.add(FaixaPreco(3L, LocalDate.of(2021, 3, 12), BigDecimal("0.05")))
    
val faixaPreco = faixas.firstOrNull { posicao.data!!.isAfter(it.dataInicial) }
  • And what is the difficulty? Your code seems ok to me.

  • With this code he is taking all the tracks that are after the position date, in case he is taking 2021/01/12 and 2021/02/12 and 2021/03/12, even if I put firstOrNull, I thought of a solution here now that is sort this Array by date, it may be that for sure!

  • The firstOrNull only returns an element, never a collection.

  • Solved, thanks for the attention val Sorted = tracks.sortedBy { it.dataInitil } val track = Sorted.last { it.start date!!. isBefore(position!!. date) || it.dateStart!!. isWhat(position!!. date) }

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.