Kotlin HashSet classKotlin HashSet is class of collection which extends AbstractMutableSet class and implements Set interface. The HashSet class store elements using hashing mechanism. It support both read and write functionality. It does not support duplicate value and does not make guarantees about the order sequence of element. HashSet class declarationConstructor of Kotlin HashSet class
Functions of Kotlin HashSet class
Property of Kotlin HashSet class
Kotlin HashSet Example 1- capacityLet's create an example of HashSet defining it capacity. Capacity defines the total number of element to be added in the HashSet. It can be increase of decrease later according to need. Output: ......traversing hashSet...... 8 2 13 5 6 Kotlin HashSet Example 2 - genericFor more specific we can provide the generic types of HashSet class using its method hashSetOf<T>(). Output: ......traversing hashSetOf1...... 8 2 13 5 6 ......traversing hashSetOf2...... Ashu Roshan Vijay Kotlin HashSet Example 3 - add() and addAll()The add() function is used to add the element in the HashSet instance whereas addAll() function add all the elements of specified collection to HashSet. Output: ......traversing hashSet...... 8 2 13 5 6 ......traversing hashSet after hashSet.addAll(intSet)...... 2 4 5 6 8 13 29 Kotlin HashSet Example 4 - size, contains() and containsAll()The size property returns a total elements present in HashMap. The contains() function returns true if the mention element in it is contained in collection whereas containsAll() function checks all the elements of specified collection is contained in this collection. Output: ......traversing hashSetOf1...... 2 4 13 29 6 15 .....hashSetOf1.size..... 6 .....hashSetOf1.contains(13)..... true ....hashSetOf1.containsAll(mySet)... true Kotlin HashSet Example 5 - remove() and removeAll()The remove() function removes the specified element from the collection if it is present whereas removeAll() function removes all the specified elements from current collection if they are present. Output: ......traversing hashSetOf1...... 2 4 13 29 6 15 .....hashSetOf1.remove(6)...... true ......traversing hashSetOf1 after remove(6)...... 2 4 13 29 15 ......hashSetOf1.removeAll(mySet)...... true ......traversing hashSetOf1 after removeAll(mySet)...... 2 13 15 Kotlin HashSet Example 6 - isEmpty() and isNotEmpty()The isEmpty() function checks the current collection is empty whereas isNotEmpty() function checks the current collection is not empty. Output: ......traversing hashSetOf1...... 2 4 13 29 6 15 .....hashSetOf1.isEmpty().... hash set is not empty .....hashSetOf1.isNotEmpty().... hash set is not empty
Next TopicKotlin Annotations
|