我的文件有四列colA,colB,colC,colD。我需要读取该文件并创建两个不可变的数据结构映射。
colA -> (colB, colC, colD)
colB -> (colA, colC, colD)
我有什么方法可以一次性做到这一点。使用for comprehension我可以创建一个Array,在迭代之后我可以创建两个Maps。但它似乎并不是正确而有效的方法。请引导我完成。
那么我正在做的是如下
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
答案 0 :(得分:3)
折叠比映射更灵活,因此您可以使用fold
一次构建两个集合:
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))