Scala集合flatten操作

一层嵌套,但是flatten的要求需要List内部类型都一样, 例如都为List

scala> List(List(1), List(2), List(3)).flatten
res4: List[Int] = List(1, 2, 3)

scala> List(List(List(1)), List(List(2)), List(List(3))).flatten
res5: List[List[Int]] = List(List(1), List(2), List(3))

多层嵌套

def flatten(ls: List[Any]): List[Any] = ls flatMap {
  case i: List[_] => flatten(i)
  case e => List(e)
}

val k = List(1, List(2, 3), List(List(List(List(4)), List(5)), List(6, 7)), 8)
flatten(k)

非同质数据类型

@Test
def test8(): Unit = {
  val l = Seq(1, Seq(2, 3))
  val r = l.flatMap { x => x match {
    case a: Seq[_] if a.size > 1 => a
    case b: Int => Seq(b)
    }
  }
  println(r)
}
List(1, 2, 3)

https://stackoverflow.com/questions/37340912/scala-flatmap-what-are-ms-and-e/37349449#37349449
https://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/
https://stackoverflow.com/questions/1737452/how-to-flatten-a-list-of-different-types-in-scala

posted @ 2023-03-10 23:10  Aitozi  阅读(125)  评论(0编辑  收藏  举报