Kotlin List.containsAll()
The Kotlin List.containsAll() function checks if all elements in the specified collection are contained in this list, and if so, the function returns true, else false.
Syntax
List.containsAll(elements)
Example 1
In this example,
- Take a list of strings: list1.
- Take another list of strings: list2.
- Call containsAll() function on list1 and pass list2 as argument to the function.
- We have take elements in list2 such that they are all present in list1. So, contiansAll() function should return true in this case.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d", "e")
val list2 = listOf("b", "e")
val result = list1.containsAll(list2)
print(result)
}
Output
true
Example 2
In this example,
- Take a list of strings: list1.
- Take another list of strings: list2.
- Call containsAll() function on list1 and pass list2 as argument to the function.
- We have take elements in list2 such that they are all not present in list1. So, contiansAll() function should return true in this case.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d", "e")
val list2 = listOf("b", "e", "w")
val result = list1.containsAll(list2)
print(result)
}
Output
false
Example 3
In this example,
- Take a list of strings: list1.
- Take a set of strings: set1.
- Call containsAll() function on list1 and pass set1 as argument to the function.
- We have take elements in set1 such that they are all present in list1. So, contiansAll() function should return true.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d", "e")
val set1 = setOf("b", "c")
val result = list1.containsAll(set1)
print(result)
}
Output
true