w3resource

Scala set: Convert a set to a list

Scala Set Exercise-9 with Solution

Write a Scala program to create a set and convert it to a list.

Sample Solution:

Scala Code:

object SetToListExample {
  def main(args: Array[String]): Unit = {
    // Create a set
    val nums = Set(1, 2, 3, 4)

    // Print the set
    println("Set: " + nums)

    // Convert the set to a list
    val list = nums.toList

    // Print the list
    println("List: " + list)
  }
}

Sample Output:

Set: Set(1, 2, 3, 4)
List: List(1, 2, 3, 4)

Explanation:

In the above exercise,

  • In this program, we create a set "nums" containing the elements 1, 2, 3, and 4.
  • To convert the set to a list, we use the toList method.
  • In the program, we convert the set to a list by using the line val list = set.toList.
  • Finally, we print the set and the converted list.

Scala Code Editor :

Previous: Find the size of a set.
Next: Checking if a set is a subset of another set.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/sets/scala-set-exercise-9.php