Scala set: Convert a set to a list
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics