Home > other >  Remove duplicates pairwise in kotlin
Remove duplicates pairwise in kotlin

Time:01-08

I have multiple lists of integers.

val firstList: ArrayList<Int> = arrayListOf(1, 1, 1, 2, 3, 4)
val secondList: ArrayList<Int> = arrayListOf(1, 4, 5, 6, 6, 6, 7, 8)
val thirdList: ArrayList<Int> = arrayListOf(1, 6, 9)

...

I need to remove duplicates only among the other lists, and not within a list itself.

The result should be:

[1,1,1,2,3,4,5,6,6,6,7,8,9]

What is the best approach to do so in Kotlin?

CodePudding user response:

We can filter the additional lists with a .filter and .contains, then add the result to the firstList. Not sure if this is the most efficient way, but it should work.

val firstList: ArrayList<Int> = arrayListOf(1, 1, 1, 2, 3, 4)
val secondList: ArrayList<Int> = arrayListOf(1, 4, 5, 6, 6, 6, 7, 8)
val thirdList: ArrayList<Int> = arrayListOf(1, 6, 9)
    
firstList  = secondList.filterNot { firstList.contains(it) }
firstList  = thirdList.filterNot { firstList.contains(it) }
    
firstList.sort() //not sure if you want the firstList to be sorted or not

You could also make it an extension function, so then it is easier to call.

fun <T> MutableCollection<T>.addOtherNoDuplicates(vararg others: Iterable<T>){
    others.forEach {other ->
        this  = other.filterNot { this.contains(it) }
    }
}

Then the call would just be:

firstList.addOtherNoDuplicates(secondList, thirdList) //add as many as you want
firstList.sort()

If you only want to use it for ArrayList, then you can replace the MutableCollection<T> with ArrayList<T> and use the sort() directly in the function itself.

CodePudding user response:

If these are very long lists, you can use a MutableSet on the side to efficiently avoid adding the unwanted values.

val input = listOf(firstList, secondList, thirdList)
val allValues = mutableSetOf<Int>()
val result = mutableListOf<Int>()
for (list in input) {
    val newValues = list.filterNot { it in allValues }
    result.addAll(newValues)
    allValues.addAll(newValues)
}

println(result)
  •  Tags:  
  • Related