Find difference between two Lists in Kotlin
This article explores different ways to find the difference between two lists in Kotlin.
1. Using minus() function
The minus() function returns a list containing all elements of the original list except the elements contained in the given specified list.
|
1 2 3 4 5 6 7 8 |
fun main() { val first = listOf(1, 3, 2, 3, 4, 1) val second = listOf(1, 3) val duplicates = first.minus(second) println(duplicates) // [2, 4] } |
To make this work with a list of objects, you should provide the implementation of the equals and hashCode functions. The list may be converted to a HashSet to speed up the operation.
2. Using removeAll() function
Alternatively, you can use the removeAll() function to remove all elements contained in the specified collection. This can be used to calculate differences between two lists, as shown below. Note that the solution converts the original list to a set, to avoid any modifications to it and to speed up the operation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> findDifference(first: List<T>, second: List<T>): List<T> { val diff = first.toMutableSet() diff.removeAll(second) return diff.toList() } fun main() { val first = listOf(1, 3, 2, 3, 4, 1) val second = listOf(1, 3) val duplicates = findDifference(first, second) println(duplicates) // [2, 4] } |
3. Using filter() function
Another option is to filter the elements of the first list that are missing in the other list. It can be done as follows, using the filter() function with the contains() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> findDifference(first: List<T>, second: List<T>): Set<T> { return first.filter { !second.contains(it) }.toSet() } fun main() { val first = listOf(1, 3, 2, 3, 4, 1) val second = listOf(1, 3) val duplicates = findDifference(first, second) println(duplicates) // [2, 4] } |
That’s all about finding the difference between two lists in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)