0

I have entry at file having four columns colA, colB, colC, colD. I need to read that file and create two immutable datastructure mappings.

colA -> (colB, colC, colD)  
colB -> (colA, colC, colD)  

Is there any way I can do that in one go. Using for comprehension I can create one Array and after iterating through it I can create two Maps. But it doesn't seems correct and efficient approach.Please guide me through.
Well what I am doing is as below

case class Mapping(col1: String, col2: String, col3: String, col4: String)
val columnList = for {
    line <- io.Source.fromInputStream(getClass.getClassLoader.getResourceAsStream(file)).getLines() if (!(line startsWith ("#")))
    val splittedArray: Array[String] = line.replaceAll(" ", "").split(",")
    if (splittedArray.length == 4) 
  } yield Mapping(splittedArray(0), splittedArray(1), splittedArray(2), splittedArray(3))
val map1 = columnList.map(mapping=> (mapping.col1, mapping)).toMap
val map2 = columnList.map(mapping=> (mapping.col2, mapping)).toMap
HKumar
  • 655
  • 1
  • 8
  • 18

1 Answers1

3

Folding is more flexible than a mapping, so you can use a fold to build up two collections at once:

val v = Vector(
  Vector(1,2,3,4),
  Vector(5,6,7,8),
  Vector(9,10,11,12))
val (m1, m2) = v.foldLeft((Map.empty[Int,(Int,Int,Int)],Map.empty[Int,(Int,Int,Int)])) {
  case ((x,y), Vector(a,b,c,d)) =>
    (x + (a -> (b,c,d)), y + (b -> (a,c,d)))
}

println(m1)
// Map(1 -> (2,3,4), 5 -> (6,7,8), 9 -> (10,11,12))
println(m2)
// Map(2 -> (1,3,4), 6 -> (5,7,8), 10 -> (9,11,12))
dhg
  • 52,383
  • 8
  • 123
  • 144