假如说:
- 所有地图键都在形式
"field[index]"
- 每个键只有一个值
Seq
。
- 如果有条目,
"email[x]"
则有条目,"password[x]"
反之亦然。
我会做这样的事情:
val request = Map(
"email[0]" -> Seq("alice@example.com"),
"email[1]" -> Seq("bob@example.com"),
"password[0]" -> Seq("%vT*n7#4"),
"password[1]" -> Seq("Bfts7B&^")
)
case class User(email: String, password: String)
val Field = """(.+)\[(\d+)\]""".r
val userList = request.groupBy { case (Field(_, idx), _) => idx.toInt }
.mapValues { userMap =>
def extractField(name: String) =
userMap.collect{case (Field(`name`, _), values) => values.head}.head
User(extractField("email"), extractField("password"))}
.toList.sortBy(_._1).map(_._2)
// Exiting paste mode, now interpreting.
request: scala.collection.immutable.Map[String,Seq[String]] = Map(email[0] -> List(alice@example.com),
email[1] -> List(bob@example.com), password[0] -> List(%vT*n7#4), password[1] -> List(Bfts7B&^))
defined class User
Field: scala.util.matching.Regex = (.+)\[(\d+)\]
userList: List[User] = List(User(alice@example.com,%vT*n7#4), User(bob@example.com,Bfts7B&^))