What is the HashSet.containsAll method in Kotlin?
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 elementsvar set: HashSet<Int> = hashSetOf<Int>()// add four entriesset.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));}
Explanation
-
Line 3: We create a new
HashSetobject with the nameset. We use thehashSetOf()method to create an emptyHashSet. -
Lines 6–9: We add four new elements,
1,2,3,4, to thesetusing theadd()method. -
Line 13: We create a new
Listobject withlist1with 2 elements[1,2]using thelistOfmethod. -
Line 15: We use the
containsAllmethod to check if all elements of thelist1are present in theset. In this case, it returnstrue, because all elements oflist1are present in theset.
Note: All elements of
list1are present in theset.
-
Line 17: We create a new
Listobject withlist2with 2 elements[1,5]using thelistOfmethod. -
Line 19: We use the
containsAllmethod to check if all elements of thelist2are present in theset. In this case,falseis returned because element5oflist2is not present in theset.
Note: Element 5 of
list2is not present in theset.