Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

What is the HashSet.containsAll method in Kotlin?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Kotlin, the containsAll method is used to check if all the elements of the passed collection are present in the HashSet object.

Syntax

fun containsAll(elements: Collection): Boolean

Parameters

This method takes the parameter, collection, to check if it is present in this set.

Return value

This method returns true if all the elements of the passed Collection are present in the set. Otherwise, it returns false.

Example

fun main() {
//create a new HashSet which can have integer type as elements
var set: HashSet<Int> = hashSetOf<Int>()
// add four entries
set.add(1)
set.add(2)
set.add(3)
set.add(4)
println("\nThe set is : $set")
val list1 = listOf(1,2);
println("\nThe list1 is : $list1")
println("set.containsAll(list1) : " + set.containsAll(list1));
val list2 = listOf(1,5);
println("\nThe list2 is : $list2")
println("set.containsAll(list2) : " + set.containsAll(list2));
}
Using the containsAll method

Explanation

  • Line 3: We create a new HashSet object with the name set. We use the hashSetOf() method to create an empty HashSet.

  • Lines 6–9: We add four new elements, 1,2,3,4, to the set using the add() method.

  • Line 13: We create a new List object with list1 with 2 elements [1,2] using the listOf method.

  • Line 15: We use the containsAll method to check if all elements of the list1 are present in the set. In this case, it returns true, because all elements of list1 are present in the set.

Note: All elements of list1 are present in the set.

  • Line 17: We create a new List object with list2 with 2 elements [1,5] using the listOf method.

  • Line 19: We use the containsAll method to check if all elements of the list2 are present in the set. In this case, false is returned because element 5 of list2 is not present in the set.

Note: Element 5 of list2 is not present in the set.

RELATED TAGS

kotlin
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring