Find difference between two lists in kotlin
This article explores different ways to get the difference between the two lists in Kotlin. The solution should return all elements that are present in one list but not there in another list.
1. Using minus() function
A simple solution is to use the minus() function to get a list containing all elements of the original collection except the elements contained in the given collection.
|
1 2 3 4 5 6 7 8 |
fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3) val difference = first.minus(second) print(difference) // [4, 5] } |
You can further convert the list into a HashSet to speed up the operation.
|
1 2 3 4 5 6 7 |
fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3) val difference = first.minus(second.toHashSet()) print(difference) // [4, 5] } |
2. Using filterNot() function
Another approach is to use the filterNot() function to get a list containing all elements which are not present in the other list. This function is demonstrated below:
|
1 2 3 4 5 6 7 8 |
fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3) val difference = first.filterNot { second.contains(it) } print(difference) // [4, 5] } |
3. Using filter() function
Alternatively, you can use the filter() function to achieve the same results.
|
1 2 3 4 5 6 7 8 |
fun main() { val first = listOf(1, 2, 3, 4, 5) val second = listOf(1, 2, 3) val difference = first.filter { !second.contains(it) } print(difference) // [4, 5] } |
That’s all about getting the difference between the 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 :)