English 中文(简体)
Scala Collections - flatten
  • 时间:2024-10-18

Scala Collections - Flatten Method


Previous Page Next Page  

flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections.

Syntax

The following is the syntax of flatten method.


def flatten[B]: Traversable[B]

Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be appped on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition.

Usage

Below is an example program of showing how to use flatten method −

Example


object Demo {
   def main(args: Array[String]) = {
      val pst = List(List(1,2), List(3,4))
      //apply operation
      val result = pst.flatten
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command


>scalac Demo.scala
>scala Demo

Output


List(1, 2, 3, 4)
Advertisements