Scala Collections List, Sequence, reduceLeft, filter, foldLeft, map and flatMap

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 04:01:01 Viewed : 527


Scala Collections List, Sequence, reduceLeft, filter, foldLeft, map and flatMap

In Scala, you can work with various collection types, including List and Seq, and perform operations like reduceLeft, filter, foldLeft, map, and flatMap. Lets explore these operations with examples:

1. Creating Lists and Sequences:

scala
val myList = List(1, 2, 3, 4, 5) val mySeq = Seq(1, 2, 3, 4, 5)

Here, we create a List named myList and a Seq named mySeq with the same elements.

2. reduceLeft:

reduceLeft is used to combine elements of a collection into a single result by applying a binary operator. For example, we can use it to find the sum of all elements:

scala
val sum = myList.reduceLeft(_ + _)

3. filter:

filter is used to create a new collection by selecting elements that satisfy a given predicate. For instance, to filter even numbers:

scala
val evenNumbers = myList.filter(_ % 2 == 0)

4. foldLeft:

foldLeft is used to accumulate a result by applying a binary operator to each element of the collection, starting with an initial value. It is a more general form of reduction:

scala
val product = myList.foldLeft(1)(_ * _)

5. map:

map applies a function to each element in the collection and returns a new collection with the results. For example, to double each element:

scala
val doubledList = myList.map(_ * 2)

6. flatMap:

flatMap is used to transform each element into a collection and then flatten the results into a single collection. It is often used when you have nested collections. For example, to create pairs of numbers:

scala
val pairs = myList.flatMap { x => List(x, x * 2) }

7. Output:

Here is how you can print the results of these operations:

scala
println("Original List: " + myList) println("Sum of Elements: " + sum) println("Even Numbers: " + evenNumbers) println("Product of Elements: " + product) println("Doubled List: " + doubledList) println("Pairs: " + pairs)

8. Complete Example:

Putting it all together:

scala
val myList = List(1, 2, 3, 4, 5) val mySeq = Seq(1, 2, 3, 4, 5) val sum = myList.reduceLeft(_ + _) val evenNumbers = myList.filter(_ % 2 == 0) val product = myList.foldLeft(1)(_ * _) val doubledList = myList.map(_ * 2) val pairs = myList.flatMap { x => List(x, x * 2) } println("Original List: " + myList) println("Sum of Elements: " + sum) println("Even Numbers: " + evenNumbers) println("Product of Elements: " + product) println("Doubled List: " + doubledList) println("Pairs: " + pairs)

Output:

mathematica
Original List: List(1, 2, 3, 4, 5) Sum of Elements: 15 Even Numbers: List(2, 4) Product of Elements: 120 Doubled List: List(2, 4, 6, 8, 10) Pairs: List(1, 2, 2, 4, 3, 6, 4, 8, 5, 10)

This example demonstrates how to use various operations on List and Seq collections in Scala, including reduceLeft, filter, foldLeft, map, and flatMap.

In Scala, map and flatMap are both higher-order functions used for working with collections, but they serve different purposes and have different behaviors. Here is an explanation of their differences along with examples:

1. map Function:

  • The map function is used to transform each element of a collection while maintaining the structure of the original collection.

  • It takes a function that operates on each element of the collection and returns a new collection with the same structure (e.g., same length) as the original.

  • The result of map is a collection of the same type (e.g., if you map a List, you get back a List).

Example of map:

Suppose we have a list of integers and want to double each element:

scala
val originalList = List(1, 2, 3, 4, 5) val doubledList = originalList.map(x => x * 2)

Output:

css
originalList: List(1, 2, 3, 4, 5) doubledList: List(2, 4, 6, 8, 10)

In this example, map transforms each element by doubling it while preserving the list structure.

2. flatMap Function:

  • The flatMap function is used when you want to transform each element of a collection into a sequence of elements and then flatten the sequences into a single collection.

  • It takes a function that operates on each element of the collection and returns a collection (often a Seq, List, or Set) for each element. The results are then flattened into a single collection.

  • The result of flatMap is typically a collection of a different type (e.g., if you flatMap a List, you might get back a List of elements or a different collection type).

Example of flatMap:

Suppose we have a list of strings representing sentences, and we want to split each sentence into words and flatten them into a single list:

scala
val sentences = List("Hello, World!", "Scala is awesome.", "Functional programming.") val words = sentences.flatMap(sentence => sentence.split(" "))

Output:

css
sentences: List("Hello, World!", "Scala is awesome.", "Functional programming.") words: List("Hello,", "World!", "Scala", "is", "awesome.", "Functional", "programming.")

In this example, flatMap splits each sentence into words, creating lists of words for each sentence, and then flattens these lists into a single list of words.

In summary, map is used for one-to-one transformations of elements, while flatMap is used when you need to transform elements into collections and flatten the result into a single collection. The choice between map and flatMap depends on your specific use case and the desired result structure.

Seq:

Creates a collection with the specified elements.

def apply[A](elems: A*): Seq[A] 

LinearSeq:

Creates a collection with the specified elements.

def apply[A](elems: A*): LinearSeq[A]

IndexedSeq:

Creates a collection with the specified elements.

def apply[A](elems: A*): IndexedSeq[A] 

List:

Converts this range to a list.

def toList: List[Int]

reduceLeft:

Applies a binary operator to all elements of this list, going left to right.

override def reduceLeft[B >: Int](op: (B, Int) => B): B

filter:

Selects all elements of this list which satisfy a predicate.

def filter(p: Int => Boolean): List[Int]

foldLeft:

Applies a binary operator to a start value and all elements of this list, going left to right.

override def foldLeft[B](z: B)(op: (B, Int) => B): B

map:

Builds a new collection by applying a function to all elements of this list.

final override def map[B, That](f: Int => B)(implicit bf: CanBuildFrom[List[Int], B, That]): That

flatMap:

Builds a new collection by applying a function to all elements of this list and using the elements of the resulting collections.

final override def flatMap[B, That](f: Int => GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[Int], B, That]): That 

Example:

Following example illustrates about Scala Collections List, Sequence, reduceLeft, filter, foldLeft, map and flatMap.

Save the file as −  SeqMainApp.scala.  

SeqMainApp.scala  

 package runnerdev

import scala.collection.immutable.LinearSeq 

object SeqMainApp extends App {

  val seq = Seq(123)

  println("seq " + seq) 

  val set = Set(123)

  println("set " + set) 

  val map = Map(1 -> "a"2 -> "b"3 -> "c")

  println("map " + map) 

  val indexedSeq = IndexedSeq(123)

  println("indexedSeq " + indexedSeq) 

  val linearSeq = LinearSeq(123)

  println("linearSeq " + linearSeq) 

  //val isOdd: Int => Boolean

  val isOdd = (elem: Int) => elem % 2 == 0

  //val isEven: Int => Boolean

  val isEven = (elem: Int) => elem % 2 != 0 

  var listMod = List(123).filter(x => x % 2 == 1)

  println("listMod " + listMod)

  var listOddFilter = List(123).filter(x => isOdd(x))

  println("listOddFilter " + listOddFilter)

  var listOdd = List(123).filter(isOdd)

  println("listOdd " + listOdd) 

  //Transformation // val lowerCapsList: List[String]

  val lowerCapsList = List("A""Cat").map(s => s.toLowerCase)

  println("lowerCapsList " + lowerCapsList) 

  //val largest: (Int, Int) => Int

  val largest = (a: Int, b: Int) => if (a > ba else b

  //Reduce

  var reduceLeft = List(86222).reduceLeft((ab) => a max b)

  println("reduceLeft " + reduceLeft)

  var reduceLeft1 = List(86222).reduceLeft((ab) => largest(ab))

  println("reduceLeft1 " + reduceLeft1) 

  var reduceLeft2 = List(86222).reduceLeft(largest)

  println("reduceLeft2 " + reduceLeft2)

  var reduceLeftmax = List(86222).reduceLeft(_ max _)

  println("reduceLeftmax " + reduceLeftmax) 

  var maxList = List(12).reduceLeft { (ab) =>

    println("(a -> b) " + (a -> b))

    a max b

  }

  println("maxList " + maxList)

  //reduceLeft throws an exception on an Nil (empty) List

  var listFoldLeft = List(1234).foldLeft(0)(_ + _)

  println("listFoldLeft " + listFoldLeft//10

  var listFoldLeft1 = List(1234).foldLeft(1)(_ * _)

  println("listFoldLeft1 " + listFoldLeft1) //24

  val n = (1 to 3).toList

  println("n " + n)

  val resultMap = n.map(i => n.map(j => i * j))

  println("resultMap " + resultMap)

  val resultFlateMap = n.flatMap(i => n.map(j => i * j))

  println("resultFlateMap " + resultFlateMap) 

} 

compile and run the above example as follows 

scala> scalac SeqMainApp.scala

scala> scala SeqMainApp 

Output:

seq List(1, 2, 3)

set Set(1, 2, 3)

map Map(1 -> a, 2 -> b, 3 -> c)

indexedSeq Vector(1, 2, 3)

linearSeq List(1, 2, 3)

listMod List(1, 3)

listOddFilter List(2)

listOdd List(2)

lowerCapsList List(a, cat)

reduceLeft 22

reduceLeft1 22

reduceLeft2 22

reduceLeftmax 22

(a -> b) (1,2)

maxList 2

listFoleLeft 10

listFoleLeft1 24

n List(1, 2, 3)

resultMap List(List(1, 2, 3), List(2, 4, 6), List(3, 6, 9))

resultFlateMap List(1, 2, 3, 2, 4, 6, 3, 6, 9)

Search
Related Articles

Leave a Comment: