D.L.
D.L.

Reputation: 169

How to map an int to a tuple and access the tuple in scala

I have an input map from an integer to a tuple of Int and Double as follow.

def doSomething(x: Seq[Map[Int, (Int, Double)]]): Int = {.....}

Now, I want to access each element of the tuple in x as follows inside doSomething.

val res = x.map({ (input, weight) => }).unzip

Then I do some computation on the input which is an Int and weight which is a double for all keys of the map. But this does not work. How can I access the tuple values from the map?

Upvotes: 0

Views: 855

Answers (3)

vindev
vindev

Reputation: 2280

You need to perform two map operation in order to access your Map values (input,weight)

x.map(_.map { case (key, (input, weight)) => /*do something with (input,weight)*/})

Upvotes: 1

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1568

You can do it using collect

scala> val seqMap :Seq[Map[Int, (Int, Double)]] = List(Map(1->(1,1.0), 2-> (2,2.0)),Map(3->(3,3.0), 4-> (4,4.0)))
seqMap: Seq[Map[Int,(Int, Double)]] = List(Map(1 -> (1,1.0), 2 -> (2,2.0)), Map(3 -> (3,3.0), 4 -> (4,4.0)))


scala>val result = seqMap.collect{
  case e => e.values.map( ele => ele._1 -> ele._2)
}.flatten
result :  Seq[(Int, Double)] = List((1,1.0), (2,2.0), (3,3.0), (4,4.0))

Upvotes: 0

Dominic Egger
Dominic Egger

Reputation: 1016

so x.map requires a function as parameter of form Map[Int,(Int,Double)] => B in your case so to get to the input and weight (assuming that's the tuple) you'll have to

x.map(
    kvMap => kvMap.map(
      kv => {
          val tuple = kv._2
          val input = tuple._1
          val weight = tuple._2
      }
    )
)

Upvotes: 0

Related Questions