Kotlin – Check if all Elements of a Collection are present in this List

To check if all elements of a collection are present in this List in Kotlin, call containsAll() function on this List and pass the collection as argument to this function.

The Kotlin List.containsAll() function checks if all elements in the specified collection (passed as argument) are contained in this list. The collection could be a list, set, etc.

Syntax of List.containsAll()

The syntax to call List.containsAll() function is

list.containsAll(elements)
ParameterDescription
elementsRequired. A Kotlin collection whose elements are checked if present in this list.

Return Value

List.contains() returns true if all the elements are present in this list, else it returns false.

ADVERTISEMENT

Example 1: Check if All Elements are in List

In this example, we will take a list of strings, say list1. We will take another list, say list2. We will use List.containsAll() to check if all elements of list2 are present in list1.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd")
    val list2 = listOf("bc", "cd")
    if (list1.containsAll(list2)) {
        print("All elements of list2 are present in list1.")
    } else {
        print("All elements of list2 are not present in list1.")
    }
}

Output

All elements of list2 are present in list1.

Example 2: List.containsAll(Set)

In this example, we will take a list of strings, list1. We will take a collection, say set, in set1. We will check if all elements of set1 are present in list1 by calling containsAll() function on list1 with set1 passed as argument to it.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd")
    val set1 = setOf("bc", "cd")
    if (list1.containsAll(set1)) {
        print("All elements of set1 are present in list1.")
    } else {
        print("All elements of set1 are not present in list1.")
    }
}

Output

All elements of set1 are present in list1.

Conclusion

In this Kotlin Tutorial, we learned how to check if this List contains all the elements of a given collection, using Kotlin List.containsAll() function.