Kotlin List containsAll()
Syntax & Examples


Syntax of List.containsAll()

The syntax of List.containsAll() function is:

abstract fun containsAll(elements: Collection<E>): Boolean

This containsAll() function of List checks if all elements in the specified collection elements are contained in this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We also create another list named list2 containing the characters 'p', 'l'.
  • Then we check if list1 contains all elements of list2 using the List containsAll() function.
  • The result, which is a Boolean value, is stored in result.
  • Since list1 contains all the elements of the list2, the expression list1.containsAll(list2) returns true.
  • Finally, we print the value of result to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val list2 = listOf(&quot;p&quot;, &quot;l&quot;);
    val result = list1.containsAll(list2);
    print(result);
}

Output

true

2 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • We also create a list named list2 containing the integers 20, 30.
  • Then we check if list1 contains all elements of list2 using the List containsAll() function.
  • The result, which is a Boolean value, is stored in result.
  • Since list1 contains all the elements of the list2, the expression list1.containsAll(list2) returns true.
  • Finally, we print the value of result to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val list2 = listOf(20, 30);
    val result = list1.containsAll(list2);
    print(result);
}

Output

true

3 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • We also create a list named list2 containing the integers 20, 30.
  • Then we check if list1 contains all elements of list2 using the List containsAll() function.
  • The result, which is a Boolean value, is stored in result.
  • Since list1 does not contain all the elements of the list2, the expression list1.containsAll(list2) returns false.
  • Finally, we print the value of result to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val list2 = listOf(40, 80);
    val result = list1.containsAll(list2);
    print(result);
}

Output

false

Summary

In this Kotlin tutorial, we learned about containsAll() function of List: the syntax and few working examples with output and detailed explanation for each example.