Kotlin List - ContainsAll() Function



The Kotlin List ContainsAll() function is used to checks whether all elements in the specified list are present in this list. If so, the function returns true. Otherwise, it returns false.

This function allows overcoming type-safety restriction of containsAll that requires passing a collection of type Collection<E>.

Syntax

Following is the syntax of Kotlin List ContainsAll() function −

fun containsAll(elements: listOf<E>): Boolean

Parameters

This function accepts another list to search in this list as a parameter.

Return value

This function returns true if all elements of the input collection are present in this list and false otherwise.

Example 1: Checking Subset Relationships.

Let's see a basic example of the ContainsAll() function to verify if one collection is a subset of another −

fun main(args: Array<String>) {
   val mainList = listOf(1, 2, 3, 4, 5)
   val subset = listOf(2, 3)
   print("Is subset available: ")
   println(mainList.containsAll(subset))
}

Output

Following is the output −

Is subset available: true

Example 2: Input Validation

This is another example of ContainsAll() function. Here, we may need to validate that user input contains specific required elements −

fun main(args: Array<String>) {
   val requiredFields = listOf("name", "email", "password")
   val userInputFields = listOf("name", "email", "password", "age")

   if (userInputFields.containsAll(requiredFields)) {
      println("Valid input!")
   } else {
      println("Missing required fields.")
   }
}

Output

Following is the output −

Valid input!

Example 3: Filter Eligibility

The following example uses the ContainsAll() function to determine if an entity meets certain criteria −

fun main(args: Array<String>) {
   val availableSkills = listOf("Kotlin", "Java", "ReactJS", "MySQL")
   val jobRequirements = listOf("Kotlin", "Java")

   if (availableSkills.containsAll(jobRequirements)) {
      println("Eligible for the job!")
   } else {
      println("Not eligible.")
   }
}

Output

Following is the output −

Eligible for the job!
kotlin_lists.htm
Advertisements