Created
November 11, 2020 20:11
-
-
Save rupeshtr78/e643077abf258a86049658338fc6f306 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package collections | |
import scala.collection.immutable | |
object ScalaForComprehension { | |
case class Person(first: String, last: String) | |
val persons: List[Person] = List( | |
Person("Rupesh", "Raghavan"), | |
Person("Roopa", "Rupesh"), | |
Person("Rhea", "Rupesh"), | |
Person("Reva", "Rupesh")) | |
val result: List[String] = for { | |
elem <- persons // generator | |
first = elem.first // definition | |
if (first.startsWith("Ru")) // filter | |
} yield first | |
val forPerson: List[String] = for { | |
p <- persons | |
firstName = p.first | |
lastNam = p.last | |
if (lastNam == "Rupesh") | |
} yield firstName.toUpperCase | |
val yieldForSeq: Seq[Int] = for (a <- 1 to 10) yield a //creates iterator | |
val yieldForIndexed: IndexedSeq[Int] = for (a <- 1 to 10) yield a //creates iterator | |
val resul23: List[String] = for (elem <- persons if (elem.last == "Rupesh")) yield elem.first | |
// FlatMap map for comprehension | |
//The for comprehension is a syntax shortcut to combine flatMap and map | |
val numbers = List(1,2) | |
val chars = List('a','b') | |
val colors = List("black", "white") | |
val flatMapComp: List[String] = numbers | |
.flatMap((number: Int) => chars.flatMap((char: Char) => colors.map((color: String) => number + "-"+ char+ "-" +color ))) | |
val forComb: List[String] = for { | |
number <- numbers | |
char <- chars | |
color <- colors | |
} yield number + "-"+ char+ "-" +color | |
//List(1-a-black, 1-a-white, 1-b-black, 1-b-white, 2-a-black, 2-a-white, 2-b-black, 2-b-white) | |
//List(1-a-black, 1-a-white, 1-b-black, 1-b-white, 2-a-black, 2-a-white, 2-b-black, 2-b-white) | |
def main(args: Array[String]): Unit = { | |
// println(result) | |
// println(forPerson) | |
println(flatMapComp) | |
println(forComb) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment