Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

tohashset
kotlin
string
communitycreator

How to use the toHashSet method of String in Kotlin

Programming Bytes

Overview

The toHashSet method returns a HashSet with all the characters of the String.

Syntax

fun CharSequence.toHashSet(): HashSet<Char>

Parameter

The toHashset method doesn’t take any parameter, but we can apply it to objects. In the example below, we’ll apply it to a string.

Return value

It returns a HashSet containing all characters of the string.

Points to note

  1. The set data structure can contain only unique elements, so there will be no duplicate characters present in the returned result.
  2. The set doesn’t maintain the order of elements, so the order of characters in a string and returned set may differ.

Code

The code below demonstrates how to use the toHashSet method:

fun main() {
  //create a new string 
  var str = "Test";
  var setFromStr = str.toHashSet();

  //print the string and the set created from string 
  println("The str is ${str}");
  println("The set created from set is ${setFromStr}");

  str = "Java";
  setFromStr = str.toHashSet();

  //print the string and the set created from string 
  println("\nThe str is ${str}");
  println("The set created from set is ${setFromStr}");

}
Coding example of toHashSet

Explanation

  • Line 3: We create a String variable str with value Test.

  • Line 4: We use the toHasSet method to get a HashSet with all the characters of the String. We get [s, T, t, e] as a result (order of elements may differ).

  • Line 10: We change the value of the str to Java.

  • Line 11: We use the toHasSet method to get a HashSet with all the characters of the String. There are two a's present in the string Java. The set cannot contain duplicate elements, so the returned HashSet has only one a. The returned result can be [a, J, v].

RELATED TAGS

tohashset
kotlin
string
communitycreator
RELATED COURSES

View all Courses

Keep Exploring