momox
momox

Reputation: 3

Elegant way from map to csv scala (flatten a map)

I have a map that looks like this :

val m1 = Map(IND1 -> List((IND1,List((AA,11), (BB,12)))), 
  IND2  ->List((IND1,List((AA,42), (BB,80)))))

The result format is :

List((IND1,11,12),(IND2,42,80))

I tried using flatMap on the values but it is not working and the only way I can get it to work is:

m1.mapValues(x => x.head._2).map(x =>(x._1,x._2(0)._2,x._2(1)._2))

This gives me the right format but I know there must be a better and more elegant way. Please help

Upvotes: 0

Views: 127

Answers (2)

Binzi Cao
Binzi Cao

Reputation: 1085

for {
    (k, valuesList)   <- m1
    (_, values)       <- valuesList
    v1::v2::Nil = values.map(_._2)
} yield (k, v1, v2)

Upvotes: 0

prayagupadhyay
prayagupadhyay

Reputation: 31232

You can use pattern match/ deconstruct on value of a Map as below,

val m1 = Map(
  "IND1" -> List(
    ("IND1", List(("AA", 11), ("BB", 12)))
    //(k,    (first        :: second  :: Nil)
  ),
  "IND2" -> List(
    ("IND1", List(("AA", 42), ("BB", 80)))
    //(k,    (first        :: second  :: Nil)
  )
)

val results = m1.map {
  case (key, ((k, (f :: s :: Nil)) :: Nil)) =>
    (key, f._2, s._2)
}

println(results) // List((IND1,11,12), (IND2,42,80))

You can go further and deconstruct f, and s as well as tuples,

val results = m1.map {
  case (key, (_, (_, first) :: (_, second) :: Nil) :: Nil) =>
    (key, first, second)
}

Upvotes: 1

Related Questions