这是我测试过的解决方案。它不处理任何故障(与原始解决方案相同)。
object ListStuff extends App {
import ListStuffMocks._
// original solution (slightly modified to actually compile and run)
var sqlColumnValuePair = List[(String, String)]()
dataProcList foreach (processor => {
val fieldName: String = processor.getWriteColumn
val sqlValue: String = processor.getSqlValue(hashMapOfFieldValuePairs.get(fieldName).get)
sqlColumnValuePair :+= ((fieldName, sqlValue))
})
val originalSolution = sqlColumnValuePair
// IMO most readable solution
val newSolution = for {
processor <- dataProcList
fieldName = processor.getWriteColumn
sqlValue = processor.getSqlValue(hashMapOfFieldValuePairs.get(fieldName).get)
} yield (fieldName, sqlValue)
// requested map-solution
val newSolution2 = dataProcList.map(
(p) => {
val fieldName = p.getWriteColumn
val sqlValue = p.getSqlValue(hashMapOfFieldValuePairs.get(fieldName).get)
(fieldName, sqlValue)
}
)
println(s"Original solution: $originalSolution")
println(s"New solution: $newSolution")
println(s"New solution #2: $newSolution2")
}
object ListStuffMocks {
object DataProcessor {
val db = Map(
"valWriteCol1" -> "sqlValWriteCol1",
"valWriteCol2" -> "sqlValWriteCol2",
"valWriteCol3" -> "sqlValWriteCol3"
)
}
class DataProcessor(writeColumn: String) {
def getWriteColumn = writeColumn
def getSqlValue(field: String): String = DataProcessor.db.get(field).get
}
val hashMapOfFieldValuePairs = Map(
"writeCol1" -> "valWriteCol1",
"writeCol2" -> "valWriteCol2",
"writeCol3" -> "valWriteCol3"
)
val dataProcList = List(
new DataProcessor("writeCol1"),
new DataProcessor("writeCol3")
)
}
输出:
原始解决方案: List((writeCol1,sqlValWriteCol1), (writeCol3,sqlValWriteCol3))
新解决方案: List((writeCol1,sqlValWriteCol1), (writeCol3,sqlValWriteCol3))
新解决方案 #2: List((writeCol1,sqlValWriteCol1), (writeCol3,sqlValWriteCol3))
EDIT1:
我不知道你为什么不想使用 for comprehension - 最后它被编译到地图调用中......但是如你所愿,我添加了一个仅使用一个地图调用(newSolution2
)的解决方案。