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

481
Visualizações
Subtract two Lists in Kotlin using a custom equal function

I have two Lists and I want to get the List containing only the elements in the first list that are not in the second one. The problem is that I need to specify a custom equal when subtracting. Let's suppose I want to use one of the fields in the entries of the lists. Let's say the id.

I implemented it this way:

list1.filter { log -> list2.none { it.id == log.id } }

or

val projection = logEntries.map { it.id }
list1.filter { it.id !in projection }

Is there a better way to do it? Please take into account that I can't set a new equal method for the class.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The way you do it is ok, but when the lists become bigger you might want to do that:

You could make the process more efficient by turning your reference list (list2) to a set first.

val referenceIds = list2.distinctBy { it.id }.toSet()

list1.filter { it.id !in referenceIds }

Background:

An ArrayList which you are most likely using has a time complexity of O(n) when you check if an element is contained. So, if the list gets bigger, it will take longer.

A HashSet on the other hand has a time complexity of O(1) when checking if an element is contained. So, if list2 becomes bigger it won't get slower.

over 4 years ago · Santiago Trujillo Relatório

0

Another approach?

fun main() {

    val list1 = listOf(0, 1, 2, 3, 4, 5)
    val list2 = listOf(2,3,4)

    println(list1.filterNotIn(list2))
}

fun <T> Collection<T>.filterNotIn(collection: Collection<T>): Collection<T> {
    val set = collection.toSet()
    return filterNot { set.contains(it) }
}

Output: [0, 1, 5]

over 4 years ago · Santiago Trujillo Relatório

0

As per comments, there's no built-in way to do this.  (Probably not for any fundamental reason; just because no-one saw a need.)

However, you can easily add one yourself.  For example, here's your first suggestion, converted to extension function:

fun <T, R> Collection<T>.minus(elements: Collection<T>, selector: (T) -> R?)
    = filter{ t -> elements.none{ selector(it) == selector(t) } }

You could then call this in the same way that a built-in function would work:

list1.minus(list2){ it.id }

(There are probably more efficient implementations, but this illustrates the idea.)

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