Scala Tuple: Create a tuple from two lists
Write a Scala program that creates a tuple from two lists.
Sample Solution:
Scala Code:
object TupleFromListsExample {
def main(args: Array[String]): Unit = {
// Create two lists
val list1 = List("Red", "Green", "Blue")
val list2 = List(1, 3, 5)
// Print said two lists
println("List1: " + list1)
println("List2: " + list2)
// Create a tuple from the lists
val new_tuple = list1.zip(list2)
// Print the tuple
println("Tuple from said two lists: " + new_tuple)
}
}
Sample Output:
List1: List(Red, Green, Blue) List2: List(1, 3, 5) Tuple from said two lists: List((Red,1), (Green,3), (Blue,5))
Explanation:
In the above exercise -
- First, we create two lists: list1 with elements "Red", "Green", and "Blue", and list2 with elements 1, 3, and 5.
- To create a tuple from these lists, we use the zip method, which combines the elements of the two lists pairwise. It returns a new collection of tuples, where each tuple contains an element from list1 and its corresponding element from list2.
- We assign the resulting tuple to the variable tuple.
- Finally, we print the tuple using println.
Scala Code Editor :
Previous: Create a tuple with squares of numbers.
Next: Swap tuple elements.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics