Mik*_*378 1 collections functional-programming scala
让我们假设这四个字符串列表:
List("123::foo")
List("456::bar")
List("123::hello")
List("456::scala")
Run Code Online (Sandbox Code Playgroud)
什么是最终的有效方式:
List("123","foo","hello")
List("456","bar","scala")
Run Code Online (Sandbox Code Playgroud)
并期望为大量的初始列表工作.
How about this ?
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val lists: List[List[String]] = List(List("123::foo"), List("456::bar"), List("123::hello"), List("456::scala"))
lists: List[List[String]] = List(List(123::foo), List(456::bar), List(123::hello), List(456::scala))
scala> val result: List[List[String]] = lists.foldLeft(Map.empty[String, List[String]]) {
| (accumulator, nextList) =>
| nextList.headOption.map(_.split("::").toList).map { // next.headOption is safe in case of `lists` is empty
| case head :: last :: Nil => // matches only on those inner lists which have a single `::`
| accumulator.get(head) match {
| case None => accumulator + (head -> (last :: Nil)) // create a record in the map only if the key i.e., `head` is new
| case Some(xs) => accumulator + (head -> (last :: xs)) // If the key exists, prepend the new `last` to the existing value list
| }
| case _ => accumulator // for all the other case matches, just return the so far accumulated map
| }.getOrElse(accumulator) // exits as a base case for 1. If the `lists` is empty 2. If the `lists` is run over completely
| }.collect { case (str, xs) => str :: xs }.toList // getting it to the List[List[String]] type
result: List[List[String]] = List(List(123, hello, foo), List(456, scala, bar))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
155 次 |
最近记录: |