Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a list of tuples in Scala

Tags:

scala

I have a sample List as below

List[(String, Object)]

How can I loop through this list using for?

I want to do something like

for(str <- strlist)

but for the 2d list above. What would be placeholder for str?

like image 608
shreekanth k.s Avatar asked Apr 04 '16 02:04

shreekanth k.s


People also ask

What is the difference between list and tuple in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.

How do you write a foreach in Scala?

Scala Map foreach() method with exampleThe foreach() method is utilized to apply the given function to all the elements of the map. Return Type: It returns all the elements of the map after applying the given function to each of them. So, the identical elements are taken only once.

Is tuple immutable in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.

Which expression is one way to iterate over a collection in Scala?

A simple for loop that iterates over a collection is translated to a foreach method call on the collection.


1 Answers

Here it is,

scala> val fruits: List[(Int, String)] = List((1, "apple"), (2, "orange"))
fruits: List[(Int, String)] = List((1,apple), (2,orange))

scala>

scala> fruits.foreach {
     |   case (id, name) => {
     |     println(s"$id is $name")
     |   }
     | }

1 is apple
2 is orange

Note: The expected type requires a one-argument function accepting a 2-Tuple. Consider a pattern matching anonymous function, { case (id, name) => ... }

Easy to copy code:

val fruits: List[(Int, String)] = List((1, "apple"), (2, "orange"))

fruits.foreach {
  case (id, name) => {
    println(s"$id is $name")
  }
}
like image 121
Charlie 木匠 Avatar answered Sep 28 '22 08:09

Charlie 木匠