shreekanth k.s
shreekanth k.s

Reputation: 125

Looping through a list of tuples in 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?

Upvotes: 11

Views: 22302

Answers (4)

Charlie 木匠
Charlie 木匠

Reputation: 2400

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")
  }
}

Upvotes: 14

xrs
xrs

Reputation: 154

I will suggest using map, filter,fold or foreach(whatever suits your need) rather than iterating over a collection using loop.

Edit 1: e.g if you want to apply some func foo(tuple) on each element

val newList=oldList.map(tuple=>foo(tuple))
val tupleStrings=tupleList.map(tuple=>tuple._1) //in your situation

if you want to filter according to some boolean condition

val newList=oldList.filter(tuple=>someCondition(tuple))

or simply if you want to print your List

oldList.foreach(tuple=>println(tuple)) //assuming tuple is printable

you can find example and similar functions here
https://twitter.github.io/scala_school/collections.html

Upvotes: 3

Tyler
Tyler

Reputation: 18187

If you just want to get the strings you could map over your list of tuples like this:

// Just some example object
case class MyObj(i: Int = 0)

// Create a list of tuples like you have
val tuples = Seq(("a", new MyObj), ("b", new MyObj), ("c", new MyObj))

// Get the strings from the tuples
val strings = tuples.map(_._1)   

// Output: Seq[String] = List(a, b, c)

Note: Tuple members are accessed using the underscore notation (which is indexed from 1, not 0)

Upvotes: 1

echo
echo

Reputation: 1291

With for you can extract the elements of the tuple,

for ( (s,o) <- list ) yield f(s,o)

Upvotes: 3

Related Questions