Saturday, March 30, 2019

Program for Reading JSON file and save to CSV file in python using Pandas/Spark

Program for Reading JSON file and save to CSV file in python using Pandas

In [1]: import pandas as pd                                                    
In [2]: import json                                                            
In [3]: import csv                                                             
In [4]: with open('/home/hadoop/git.json', 'r') as f:
   ...:     dicts = json.load(f)
   ...:                                                      
In [5]: from pandas.io.json import json_normalize            
In [6]: df = pd.DataFrame(dicts)                             
In [7]: df.dtypes                                            
Out[7]:
assignee              object
assignees             object


                                                                                                                               
Out[9]:
                                                title                                             labels            created_at            updated_at closed_at
0   #607   [{'id': 167756, 'node_id': 'MDU6TGFiZWwxNjc3NT]  2019-03-29T02:20:18Z  2019-03-29T02:20:40      None
1                            Share [{'id': 57548, 'node_id': 'MDU6TGFiZWw1NzU0OA'] 2019-03-29T02:17:52  2019-03-29T02:18:17      None
2        Setup  [{'id': 57548, 'node_id': 'MDU6TGFiZWw1NzU0OA']  2019-03-29T02:16:59Z  2019-03-29T02:17:36Z      None

n [89]: df1=df['title','labels','created_at','updated_at','closed_at']]  
                                                                                                                             
In [90]: df1.to_csv("/home/hadoop/file.csv", encoding="utf-8")        

Program for Reading JSON file and save to CSV file in SPARK

scala> val df = spark.read.option("multiline","true").option("inferschema","true").format("json").load("/home/hadoop/Desktop/vow/ramesh.json")
scala> df.select($"title" as "title",$"labels.name" as "name",$"created_at" as "created_at", $"updated_at" as "updated_at", $"closed_at" as "closed_at").show



scala> df.select($"title" as "title",$"labels.name" as "name",$"created_at" as "created_at", $"updated_at" as "updated_at", $"closed_at" as "closed_at").show
+--------------------+--------------------+--------------------+--------------------+---------+
|               title|                name|          created_at|          updated_at|closed_at|
+--------------------+--------------------+--------------------+--------------------+---------+

Space into Comma Transformation for Dataframe data using Spark with Scala

Space into Comma Transformation for Dataframe data using Spark with Scala



// Transforming Space into Comma in Dataframe data
scala> val obj = List( (1001, "7 2234 2342 2522"), (1002, "2222 2223 2224 2225"), (1003, "2000 2001 2002 2003 2004"), (1004, "2005 2006 2000 7 2001 2010"))
obj: List[(Int, String)] = List((1001,7 2234 2342 2522), (1002,2222 2223 2224 2225), (1003,2000 2001 2002 2003 2004), (1004,2005 2006 2000 7 2001 2010))


scala> val r1 = sc.parallelize(obj);
r1: org.apache.spark.rdd.RDD[(Int, String)] = ParallelCollectionRDD[1] at parallelize at :26

scala>  r1.foreach(println)
(1001,7 2234 2342 2522)
(1002,2222 2223 2224 2225)
(1003,2000 2001 2002 2003 2004)
(1004,2005 2006 2000 7 2001 2010)


 case class UserStory(userid:String, storyid:String)

 val r2 = r1.map (x => {
       val userid = x._1.toString
       val storyid = x._2.toString
       UserStory(userid,storyid)
       })
 
scala> r2.foreach(println)
UserStory(1001,7 2234 2342 2522)
UserStory(1002,2222 2223 2224 2225)
UserStory(1003,2000 2001 2002 2003 2004)
UserStory(1004,2005 2006 2000 7 2001 2010)


scala> val df = r2.toDF
df: org.apache.spark.sql.DataFrame = [userid: string, storyid: string]

scala> df.printSchema
root
 |-- userid: string (nullable = true)
 |-- storyid: string (nullable = true)


scala> df.show
+------+--------------------+
|userid|             storyid|
+------+--------------------+
|  1001|    7 2234 2342 2522|
|  1002| 2222 2223 2224 2225|
|  1003|2000 2001 2002 20...|
|  1004|2005 2006 2000 7 ...|
+------+--------------------+

scala> import org.apache.spark.sql.functions._
import org.apache.spark.sql.functions._

scala> df.select(col("userid") as "user id",regexp_replace(col("storyid")," ",",") as "story id").show
+-------+--------------------+
|user id|            story id|
+-------+--------------------+
|   1001|    7,2234,2342,2522|
|   1002| 2222,2223,2224,2225|
|   1003|2000,2001,2002,20...|
|   1004|2005,2006,2000,7,...|
+-------+--------------------+

Scala crash courses with examples




Scala Crash Course 


scala> val myIntArray:Array[Int] = new Array(3)
myIntArray: Array[Int] = Array(0, 0, 0)

scala> myIntArray
res0: Array[Int] = Array(0, 0, 0)

scala> myIntArray.foreach(println)
0
0
0

scala> myIntArray(0)=10

scala> myIntArray(1)=20

scala> myIntArray(2)=30

scala> myIntArray.foreach(println)
10
20
30


scala> def addOne(x:Int): Int = {
     | x+1
     | }
addOne: (x: Int)Int

scala> addOne(5)
res6: Int = 6

scala> addOne(50)
res7: Int = 51


 scala> def addTwo(x:Int):Int = {
     | return x + 2;
     | }
addTwo: (x: Int)Int

scala> addTwo(5);
res8: Int = 7

scala> (1 to 10).foreach(x => println(addTwo(x)))
3
4
5
6
7
8
9
10
11
12


scala> def max(x:Int, y:Int): Int = {
     | if (x > y) x else y
     | }
max: (x: Int, y: Int)Int

scala> max(5,6)
res22: Int = 6


scala> val myArray = Array("Zara","Lara","Sara")
myArray: Array[String] = Array(Zara, Lara, Sara)

scala> var i = 0
i: Int = 0

scala> while (i < myArray.length) {
     | println(myArray(i))
     | i += 1
     | }
Zara
Lara
Sara

scala> myArray.foreach(arg => println(arg))
Zara
Lara
Sara

scala> myArray.foreach(println(_))
Zara
Lara
Sara

scala> myArray.foreach(println)
Zara
Lara
Sara



scala> for(arg <- br="" myarray="">     | println(arg)
Zara
Lara
Sara


$ cat hello.sc
object hello{
def main(args:Array[String]):Unit = {
  println("Hello : " + args(0) + " !")
}
}

scala> :load /home/hadoop/Desktop/ScalaTraining/hello.sc
Loading /home/hadoop/Desktop/ScalaTraining/hello.sc...
defined object hello

scala> hello.main(Array("Sara"))
Hello : Sara !







scala> val word = "India!"
word: String = India!

scala> var n = 5
n: Int = 5

scala> var i = 0
i: Int = 0

scala> while (i < n){
     | println(word)
     | i += 1
     | }
India!
India!
India!
India!
India!

scala> (1 to n).foreach(x => println(word + " #" + x))
India! #1
India! #2
India! #3
India! #4
India! #5





$ cat Hello.scala
object Hello extends App{
println("Hello, World!")
}

scala> :load /home/hadoop/Desktop/ScalaTraining/Hello.scala
Loading /home/hadoop/Desktop/ScalaTraining/Hello.scala...
defined object Hello

scala> Hello.main(null)
Hello, World!



scala> 1 to n
res41: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)

scala> (1).to(5)
res42: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)



scala> val greetStrings : Array[String] = new Array[String](3)
greetStrings: Array[String] = Array(null, null, null)

scala> greetStrings(0) = "Hello"

scala> greetStrings(1) = ", "

scala> greetStrings(2) = " world! \n"

scala> greetStrings.apply(0)
res47: String = Hello

scala> def printArgs(args:Array[String]):Unit = {
     | var i = 0
     | while (i < args.length) {
     | println(args(i))
     | i += 1
     | }
     | }
printArgs: (args: Array[String])Unit

scala> printArgs(greetStrings)
Hello
,
 world!


scala> printArgs(Array("I","Love","India"))
I
Love
India


scala> def printArgs(args:Array[String]): Unit = {
     | for (arg < args)
:2: error: '<- br="" but="" expected="" found.="">for (arg < args)
               ^

scala> def printArgs(args:Array[String]): Unit = {
     | for (arg <- args="" br="">     | println(arg)
     | }
printArgs: (args: Array[String])Unit

scala> printArgs(greetStrings)
Hello
,
 world!


scala> printArgs(Array("I","Love","India"))
I
Love
India


scala> Array("Siva "," Lara", " Mala").mkString("\t")
res56: String = Siva Lara Mala

scala> println(Array("Siva "," Lara", " Mala").mkString("\t"))
Siva Lara Mala

scala> println(Array(" Siva "," Lara", " Mala").mkString("\n"))
 Siva
 Lara
 Mala

scala> println(Array(" Siva "," Lara", " Mala").mkString(":"))
 Siva : Lara: Mala


scala> def formatArgs(args:Array[String]):String = return args.mkString("\n")
formatArgs: (args: Array[String])String


scala> formatArgs(Array("sare","gare"))
res63: String =
sare
gare

scala> formatArgs(Array("sare","gare")).foreach(println)
s
a
r
e


g
a
r
e


scala> myArray
res65: Array[String] = Array(Zara, Lara, Sara)

scala> formatArgs(myArray)
res66: String =
Zara
Lara
Sara


scala> def formatArgs(args:Array[String]):String = return args.mkString(":")
formatArgs: (args: Array[String])String

scala> formatArgs(myArray)
res67: String = Zara:Lara:Sara


scala> val res = formatArgs(Array("zero","one","two"))
res: String = zero:one:two

scala> assert(res == "zero:one:two")

scala> val numNames = Array("zero","one","two")
numNames: Array[String] = Array(zero, one, two)

scala> val numNames = Array.apply("zero","one","two")
numNames: Array[String] = Array(zero, one, two)

scala> numNames.exists(s => s.contains("z"))
res72: Boolean = true



scala> val oneTwo  = List(1,2,3)
oneTwo: List[Int] = List(1, 2, 3)

scala> val threeFour = List(3,4)
threeFour: List[Int] = List(3, 4)

scala> val oneTwoThreeFour  = oneTwo ::: threeFour
oneTwoThreeFour: List[Int] = List(1, 2, 3, 3, 4)


scala> val twoThree = List(2,3)
twoThree: List[Int] = List(2, 3)


scala> val oneTwoThree = 1 :: twoThree
oneTwoThree: List[Int] = List(1, 2, 3)



scala> val thrill = "will " :: "fill " :: "until " :: Nil
thrill: List[String] = List("will ", "fill ", "until ")

scala> thrill.head
res75: String = "will "

scala> thrill.length
res76: Int = 3

scala> thrill.last
res77: String = "until "


scala> val len = thrill.length
len: Int = 3

scala> thrill(len-1)
res78: String = "until "


scala> thrill
res85: List[String] = List("will ", "fill ", "until ")

scala> thrill.filter(x => x.contains("fill"))
res86: List[String] = List("fill ")

scala> thrill.filterNot(x => x.contains("fill"))
res87: List[String] = List("will ", "until ")

Partially applied functions:
-----------------------------
scala> def origFunc(a:Int, b:Int) = a+b
origFunc: (a: Int, b: Int)Int

scala> def modFunc = origFunc(10,_:Int)
modFunc: Int => Int

scala> modFunc(10)
res89: Int = 20

scala> modFunc(103)
res90: Int = 113


named parameters:
-----------------
scala> def speed(distance:Float, time:Float)  = distance / time
speed: (distance: Float, time: Float)Float

scala> speed(time=4.5F, distance=10F)
res91: Float = 2.2222223

scala> speed(distance=100F,time=5.5F)
res92: Float = 18.181818


scala> thrill
res93: List[String] = List("will ", "fill ", "until ")

scala> thrill.sorted
res94: List[String] = List("fill ", "until ", "will ")

scala> thrill.map(s => s + "y")
res95: List[String] = List(will y, fill y, until y)

scala> thrill.map(s => s.trim() + "y")
res96: List[String] = List(willy, filly, untily)

scala> thrill
res99: List[String] = List("will ", "fill ", "until ")

scala> val thrill = List("I","Love","India")
thrill: List[String] = List(I, Love, India)

scala> val thrill  = List("Will","Fill","Until")
thrill: List[String] = List(Will, Fill, Until)

scala> thrill.map(s => s + "y")
res100: List[String] = List(Willy, Filly, Untily)

scala> val thrill = "will" :: "will" :: "until" :: Nil
thrill: List[String] = List(will, will, until)

scala> thrill.map(s => s+ "y")
res0: List[String] = List(willy, willy, untily)

scala> thrill.mkString(",")
res1: String = will,will,until

scala> thrill.mkString("$")
res2: String = will$will$until

scala> thrill.mkString(":")
res3: String = will:will:until

scala> thrill.sortBy(s => s.charAt(0).toLower)
res7: List[String] = List(until, will, will)

scala> val pair = (99,"LuftBallons")
pair: (Int, String) = (99,LuftBallons)

scala> println(pair._1)
99

scala> println(pair._2)
LuftBallons


scala> val largeTuple = ('u','r',"the",1,4,"me")
largeTuple: (Char, Char, String, Int, Int, String) = (u,r,the,1,4,me)



// mutable Set example
scala> import scala.collection.mutable.Set
import scala.collection.mutable.Set

scala> val movieSet = Set("Hitch","Poltergeist")
movieSet: scala.collection.mutable.Set[String] = Set(Poltergeist, Hitch)

scala> movieSet += "Shrek"
res12: movieSet.type = Set(Poltergeist, Shrek, Hitch)

scala> println(movieSet)
Set(Poltergeist, Shrek, Hitch)



//Immutable Set Example
scala> import scala.collection.immutable.Set
import scala.collection.immutable.Set

scala> val movieSet = Set("Hitch","Poltergeist")
movieSet: scala.collection.immutable.Set[String] = Set(Hitch, Poltergeist)

scala> movieSet += "Shrek"
:29: error: value += is not a member of scala.collection.immutable.Set[String]
  Expression does not convert to assignment because receiver is not assignable.
       movieSet += "Shrek"
                ^

scala> println(movieSet)
Set(Hitch, Poltergeist)



scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map

scala> val treasureMap = Map[Int,String]()
treasureMap: scala.collection.mutable.Map[Int,String] = Map()

scala> treasureMap += (1 -> "Go to Island")
res16: treasureMap.type = Map(1 -> Go to Island)

scala> treasureMap += (2 -> "Find Big X on Ground")
res17: treasureMap.type = Map(2 -> Find Big X on Ground, 1 -> Go to Island)

scala> treasureMap += (3 -> "Dig.")
res18: treasureMap.type = Map(2 -> Find Big X on Ground, 1 -> Go to Island, 3 -> Dig.)

scala> println(treasureMap)
Map(2 -> Find Big X on Ground, 1 -> Go to Island, 3 -> Dig.)

scala> treasureMap.foreach(println)
(2,Find Big X on Ground)
(1,Go to Island)
(3,Dig.)


//Immutable Map but val
scala> import scala.collection.immutable.Map
import scala.collection.immutable.Map

scala> val romanNumeral = Map(1 -> "I", 2 -> "II")
romanNumeral: scala.collection.immutable.Map[Int,String] = Map(1 -> I, 2 -> II)

scala> romanNumeral += (3 -> "III")
:32: error: value += is not a member of scala.collection.immutable.Map[Int,String]
  Expression does not convert to assignment because receiver is not assignable.
       romanNumeral += (3 -> "III")
                    ^

//Immutable Map but var
scala> import scala.collection.immutable.Map
import scala.collection.immutable.Map

scala> var romanNumeral = Map(1->"I",2 -> "II")
romanNumeral: scala.collection.immutable.Map[Int,String] = Map(1 -> I, 2 -> II)

scala> romanNumeral += (3 -> "III")

scala> println(romanNumeral)
Map(1 -> I, 2 -> II, 3 -> III)




// Execption handling...
scala> def getContent(filePath:String) = {
     | for(line <- br="" filepath="" getlines="" source.fromfile="">     | println(line.length + " " + line)
     | }
getContent: (filePath: String)Unit

scala> getContent("")
java.io.FileNotFoundException:  (No such file or directory)
  at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.(FileInputStream.java:138)
  at scala.io.Source$.fromFile(Source.scala:91)
  at scala.io.Source$.fromFile(Source.scala:76)
  at scala.io.Source$.fromFile(Source.scala:54)
  at getContent(:37)
  ... 54 elided


scala> getContent("/home/hadoop/Desktop/emp_data.csv")
52 empno,ename,designation,manager,hire_date,sal,deptno
39 7369,SMITH,CLERK,7902,12/17/1980,800,20
42 7499,ALLEN,SALESMAN,7698,2/20/1981,1600,30
41 7521,WARD,SALESMAN,7698,2/22/1981,1250,30
41 7566,TURNER,MANAGER,7839,4/2/1981,2975,20
43 7654,MARTIN,SALESMAN,7698,9/28/1981,1250,30
41 7698,MILLER,MANAGER,7839,5/1/1981,2850,30


//Exception Handling
scala> def getContent(filePath:String) = {
     |    try{
     |        for (line <- br="" filepath="" getlines="" source.fromfile="">     |        println(line.length + " " + line)
     |        }
     |     catch{
     |           case e: java.io.FileNotFoundException => println("No file found")
     |     }
     |   }
getContent: (filePath: String)Unit

scala> getContent("")
No file found

scala> getContent("/home/hadoop/Desktop/emp_Nosuchfile.csv")
No file found




//Partial functions
scala> def SalaryCalculator(base:Int, inc:Int, varComp:Int):Int  = base + inc + varComp
SalaryCalculator: (base: Int, inc: Int, varComp: Int)Int

scala> def jrSalCalc = SalaryCalculator(10,_:Int,_:Int)
jrSalCalc: (Int, Int) => Int

scala> def MidSalCalc = SalaryCalculator(20,_:Int, _:Int)
MidSalCalc: (Int, Int) => Int

scala> def SeniorCalc = SalaryCalculator(30, _:Int, _:Int)
SeniorCalc: (Int, Int) => Int

scala> SalaryCalculator(35,10,12)
res0: Int = 57

scala> jrSalCalc(10,12)
res1: Int = 32

scala> MidSalCalc(10,12)
res2: Int = 42

scala> SeniorCalc(10,12)
res3: Int = 52





// named arguments
scala> def speed(distance:Float, time:Float)  = distance / time
speed: (distance: Float, time: Float)Float

scala> def speed(distance:Float=10F, time:Float=2F) = distance / time
speed: (distance: Float, time: Float)Float

scala> speed(time=4F)
res5: Float = 2.5

scala> speed(10,4.5F)
res6: Float = 2.2222223

scala> speed(time=4.5F,distance=10F)
res7: Float = 2.2222223

scala> speed()
res8: Float = 5.0

scala> speed(distance=10F)
res9: Float = 5.0

scala> speed(distance=10F,time=4.5F)
res10: Float = 2.2222223




// Pattern matching example
scala> val myStr = "Hello"
myStr: String = Hello

scala> val result = myStr match {
       case "Hello" => println("Greeting!")
       case "Hi" => println("Short Greeting!")
       case _ => println("Unknown")
       }
Greeting!
result: Unit = ()


scala> val myStr = "Hello"
myStr: String = Hello

scala> val result = myStr match {
     | case "Hello" => println("Greeting!")
     | case "Hi" => println("Short Greeting!")
     | case _ => println("Unknown")
     | }
Greeting!
result: Unit = ()

scala> def UsingMatchPatternExa(myStr:String) = {
     |  val result = myStr match {
     |        case "Hello" => println("Greeting!")
     |        case "Hi" => println("Short Greeting!")
     |        case _ => println("Unknown")
     |        }
     | }
UsingMatchPatternExa: (myStr: String)Unit

scala> UsingMatchPatternExa("Hello")
Greeting!

scala> UsingMatchPatternExa("Hi")
Short Greeting!

scala> UsingMatchPatternExa("Hey")
Unknown




scala> var a = 0
a: Int = 0

scala> var b = 0
b: Int = 0

scala> for (a <- 1="" 3="" b="" br="" to="" until="">     | println("Value of a : " + a + ", b: " + b)
     | }
Value of a : 1, b: 1
Value of a : 1, b: 2
Value of a : 2, b: 1
Value of a : 2, b: 2
Value of a : 3, b: 1
Value of a : 3, b: 2




scala> val numList = List(1 to 10)
numList: List[scala.collection.immutable.Range.Inclusive] = List(Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

scala> for (a <- br="" numlist="">     | println("Value of a : " + a)
     | }
Value of a : Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)




scala> val numList = List(1 to 10)
numList: List[scala.collection.immutable.Range.Inclusive] = List(Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

scala> for (a <- br="" numlist="">     | println("Value of a : " + a)
     | }
Value of a : Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)


scala> val numList = List(1,2,3,4,5,6)
numList: List[Int] = List(1, 2, 3, 4, 5, 6)

scala> val retVal = numList.filter( x => x != 3 && x < 6)
retVal: List[Int] = List(1, 2, 4, 5)

scala> val retVal = for(a <- 3="" 6="" a="" br="" if="" numlist="" yield="">retVal: List[Int] = List(1, 2, 4, 5)




/// variable arguments
scala> def printStrings(args: String*) = {
     | var i:Int = 0
     | for (arg <- args="" br="">     | println("Arg Value[" + i + "] = " + arg)
     | i = i + 1;
     | }
     | }
printStrings: (args: String*)Unit

scala> printStrings("Hadoop","Scala","Spark","Oozie","Hive","Hbase")
Arg Value[0] = Hadoop
Arg Value[1] = Scala
Arg Value[2] = Spark
Arg Value[3] = Oozie
Arg Value[4] = Hive
Arg Value[5] = Hbase

scala> printStrings("Arun","Prasad")
Arg Value[0] = Arun
Arg Value[1] = Prasad


// Anonymous functions
scala> var inc = (x: Int) => x + 1
inc: Int => Int =

scala>

scala> inc(7)
res3: Int = 8

scala> inc(7) - 10
res4: Int = -2

scala> var mul = (x:Int, y:Int) => x * y
mul: (Int, Int) => Int =

scala> mul(5,7)
res5: Int = 35

scala> var userDir = () => { System.getProperty("user.dir")}
userDir: () => String =

scala> println(userDir())
/home/hadoop




//Higher Order function0
//(x:A) --> x's type is A. So A is a type
//A means Any Type

scala> def apply(f:Int => String, v:Int) = f(v)
apply: (f: Int => String, v: Int)String

scala> def CurlyIt[A] (x: A) = "{" + x.toString() + "}"
CurlyIt: [A](x: A)String

scala> def SquareIt[A](x: A) = "[" + x.toString() + "]"
SquareIt: [A](x: A)String

scala> SquareIt(10)
res9: String = [10]

scala> CurlyIt(20)
res10: String = {20}

scala> println(apply(SquareIt,10))
[10]

scala> println(apply(CurlyIt,20))
{20}

scala> SquareIt("sare")
res14: String = [sare]

scala> CurlyIt("sare")
res15: String = {sare}






//Higher Order function
scala> def apply(f:String => String, v:String) = f(v)
apply: (f: String => String, v: String)String

scala> def CurlyIt[A] (x: A) = "{" + x.toString() + "}"
CurlyIt: [A](x: A)String

scala> def SquareIt[A](x: A) = "[" + x.toString() + "]"
SquareIt: [A](x: A)String

scala> println(apply(SquareIt,"--Sare--"))
[--Sare--]

scala> println(apply(CurlyIt,"--Sare--"))
{--Sare--}




// Partially applied function

scala> def adder (m:Int, n:Int, p:Int) = m + n + p
adder: (m: Int, n: Int, p: Int)Int

scala> val add2 = adder(2, _:Int, _:Int)
add2: (Int, Int) => Int =

scala> add2(10,2)
res19: Int = 14

scala> add2(1,1)
res20: Int = 4

scala> def adder(m:Int)(n:Int)(p:Int) = m + n + p
adder: (m: Int)(n: Int)(p: Int)Int

scala> adder(2)(3)(4)
res21: Int = 9

/*
Scala collections can be mutable and immutable
Mutable collections can be updated or extended in place.
Immutable collections never change: Additions, Removals, Updates operators return a new collection and leave the old collection unchanged
*/

Arrays :
Fixed size sequential collection of elements of the same type
Lists :
Sequential collection of elements of the same type
Immutable
Lists represents a Linked List
Sets
Maps
Tuples
Fixed number of items of different types together
Immutable
Option



scala> val myList = List(1,2,3)
myList: List[Int] = List(1, 2, 3)

scala> val ourList = 1 :: 2 :: 3 :: Nil
ourList: List[Int] = List(1, 2, 3)

// Add Leader -- Adding an element to the head of a list
scala> val AddLeaderList = 0 :: myList
AddLeaderList: List[Int] = List(0, 1, 2, 3)

//Add Follower -- Adding an element to the tail of a list
scala> val AddFollowerList = ourList :+ 4
AddFollowerList: List[Int] = List(1, 2, 3, 4)

// List concatenation
scala> val t3 = myList ::: ourList
t3: List[Int] = List(1, 2, 3, 1, 2, 3)

// remove duplicates
scala> t3.distinct
res23: List[Int] = List(1, 2, 3)



scala>
Left: List[String] = List(Arun, Banu, Chitra)

scala> val Right = List("Sara","Tanu","Umesh")
Right: List[String] = List(Sara, Tanu, Umesh)

scala> Left ::: Right
res27: List[String] = List(Arun, Banu, Chitra, Sara, Tanu, Umesh)

//List concatenation
scala> Right ::: Left
res28: List[String] = List(Sara, Tanu, Umesh, Arun, Banu, Chitra)


scala> Left.union(Right)
res30: List[String] = List(Arun, Banu, Chitra, Sara, Tanu, Umesh)

scala> Right.union(Left)
res31: List[String] = List(Sara, Tanu, Umesh, Arun, Banu, Chitra)


scala> val t = (10,"Twenty",30,"Fourty",true,3.5F)
t: (Int, String, Int, String, Boolean, Float) = (10,Twenty,30,Fourty,true,3.5)

scala> t._1
res35: Int = 10




//Sets
scala> val numberSet = Set(0,1,2,3,4,5,6,7,8, 9,10)
numberSet: scala.collection.immutable.Set[Int] = Set(0, 5, 10, 1, 6, 9, 2, 7, 3, 8, 4)


scala> numberSet.filter ( _ % 2 == 0)
res39: scala.collection.immutable.Set[Int] = Set(0, 10, 6, 2, 8, 4)

scala> numberSet.filter ( _ % 2 != 0)
res40: scala.collection.immutable.Set[Int] = Set(5, 1, 9, 7, 3)

// Set doesn't keep duplicates. It keeps unique only
scala> val noDuplicates = Set(1,2,3,2,3,1,2,3,4,3,2,1,2,34,5,4,3,2,1)
noDuplicates: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 34, 3, 4)

scala> noDuplicates.foreach(println)
5
1
2
34
3
4







scala> def toInt(in : String) : Option[Int] = {
     | try{
     | Some(Integer.parseInt(in.trim))
     | } catch {
     | case e:NumberFormatException => None
     | }
     | }
toInt: (in: String)Option[Int]

scala> val someString = "123"
someString: String = 123

scala> toInt(someString) match {
     | case Some(i) => println(i)
     | case None => println(" Failed ")
     | }
123

scala> val someString = "sare"
someString: String = sare

scala> toInt(someString) match {
     | case Some(i) => println(i)
     | case None => println(" Failed ")
     | }
 Failed

scala> toInt(someString).getOrElse(-1)
res44: Int = -1

scala> toInt("10101").getOrElse(-1)
res45: Int = 10101

scala> toInt("Aries").getOrElse("Format Error")
res47: Any = Format Error





scala> val countryCapitals = Map ("India"->"Delhi","Afhanistan"->"Kabul","Egypt"->"Cairo")
countryCapitals: scala.collection.immutable.Map[String,String] = Map(India -> Delhi, Afhanistan -> Kabul, Egypt -> Cairo)

scala> countryCapitals.get("Egypt")
res48: Option[String] = Some(Cairo)

scala> countryCapitals.get("Egypt").isDefined
res49: Boolean = true

scala> countryCapitals.get("China").getOrElse("Not Defined in our list")
res51: String = Not Defined in our list





// zip example
scala> val numbers = List(1,2,3,4,5)
numbers: List[Int] = List(1, 2, 3, 4, 5)

scala> val chars  = List("a","b","c","d","e")
chars: List[String] = List(a, b, c, d, e)

scala> numbers.zip(chars)
res52: List[(Int, String)] = List((1,a), (2,b), (3,c), (4,d), (5,e))

scala> chars.zip(numbers)
res54: List[(String, Int)] = List((a,1), (b,2), (c,3), (d,4), (e,5))



// zipWithIndex example
scala> val myList = List("Arun","Prasad","Kalai","Harini","Nila","Silva")
myList: List[String] = List(Arun, Prasad, Kalai, Harini, Nila, Silva)

scala> myList.zipWithIndex
res55: List[(String, Int)] = List((Arun,0), (Prasad,1), (Kalai,2), (Harini,3), (Nila,4), (Silva,5))

scala> myList.zipWithIndex.foreach(println)
(Arun,0)
(Prasad,1)
(Kalai,2)
(Harini,3)
(Nila,4)
(Silva,5)


scala> myList.zip(List(1,2,3,4,5,6))
res57: List[(String, Int)] = List((Arun,1), (Prasad,2), (Kalai,3), (Harini,4), (Nila,5), (Silva,6))

scala> List(1,2,3,4,5,6).zip(myList)
res58: List[(Int, String)] = List((1,Arun), (2,Prasad), (3,Kalai), (4,Harini), (5,Nila), (6,Silva))



//fold left
scala> val numbers = List(1,2,3,4,5,6,7,8,9,10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

// with Seed value as 0
scala> numbers.foldLeft(0) { (m,n) => println("m : " + m + " n: " + n ); m + n}
m : 0 n: 1
m : 1 n: 2
m : 3 n: 3
m : 6 n: 4
m : 10 n: 5
m : 15 n: 6
m : 21 n: 7
m : 28 n: 8
m : 36 n: 9
m : 45 n: 10
res59: Int = 55

// with Seed value as 5
scala> numbers.foldLeft(5) { (m,n) => println("m : " + m + " n: " + n ); m + n}
m : 5 n: 1
m : 6 n: 2
m : 8 n: 3
m : 11 n: 4
m : 15 n: 5
m : 20 n: 6
m : 26 n: 7
m : 33 n: 8
m : 41 n: 9
m : 50 n: 10
res60: Int = 60



// fold Right

scala> val numbers = List(1,2,3,4,5,6,7,8,9,10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> numbers.foldRight(0) { (m,n) => println("m : " + m + " n: " + n ); m + n}
m : 10 n: 0
m : 9 n: 10
m : 8 n: 19
m : 7 n: 27
m : 6 n: 34
m : 5 n: 40
m : 4 n: 45
m : 3 n: 49
m : 2 n: 52
m : 1 n: 54
res61: Int = 55


//with seed value as 5
scala> numbers.foldRight(5) { (m,n) => println("m : " + m + " n: " + n ); m + n}
m : 10 n: 5
m : 9 n: 15
m : 8 n: 24
m : 7 n: 32
m : 6 n: 39
m : 5 n: 45
m : 4 n: 50
m : 3 n: 54
m : 2 n: 57
m : 1 n: 59
res62: Int = 60


//flatten
//It collapses one level of nested structure

cala> List(List(1,2,3),List(3,4,5),List(5,6,7)).flatten
res63: List[Int] = List(1, 2, 3, 3, 4, 5, 5, 6, 7)

scala> List(List(1,2,3),List(3,4,5),List(5,6,7)).flatten.toSet
res64: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 4)

scala> List(List(1,2,3),List(3,4,5),List(5,6,7)).flatten.distinct
res65: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

class Calculator(brand:String){
  val color: String = if (brand =="TI"){     
                "blue"     
                } else if (brand =="HP"){     
                "black"     
               } else {     
                "white"     
           } 
  def add(m:Int, n:Int) : Int = m + n 
 def displayBrandAndColor()={ 
println("Brand : " + brand + ", Color : " + color)     
 }defined class Calculator
}
scala>

scala> val calc = new Calculator("HP")
calc: Calculator = Calculator@51d6e3ae

scala> println(calc.color)
black





cala> class Calculator(brand:String){
     |   val color: String = if (brand =="TI"){
     |                 "blue"
     |                 } else if (brand =="HP"){
     |                 "black"
     |                } else {
     |                 "white"
     |            }
     |   def add(m:Int, n:Int) : Int = m + n
     |  def displayBrandAndColor()={
     |   println("Brand : " + brand + ", Color : " + color)
     |  }
     | }
defined class Calculator

scala> val c = new Calculator("HP")
c: Calculator = Calculator@67885e1f

scala> c.displayBrandAndColor
Brand : HP, Color : black

Sunday, March 24, 2019

GIT Repository commands for Developers

//rameshgit12
//Rajammal12
Install the Gitbash shell on windows and create GITUB account on your own

Initialize the repository
git init -->initialize the repository
Reinitialized existing Git repository in C:/Users/Nethra/git/.git/

Add your remote server to the origin
git remote add origin https://github.com/rameshgit12/Spark.git
Nethra@LAPTOP-JR9FSSG9 MINGW64 ~/git (master)

Clone the remote server datas to your local
$ git clone https://github.com/rameshgit12/Spark.git
Cloning into 'Spark'...
remote: Enumerating objects: 6, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 6 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (6/6), done.
Log on in GIT Bash file:
Nethra@LAPTOP-JR9FSSG9 MINGW64 ~/git (master)

Give the Username and Email credential
$  git config --global user.email "rameshexpnet@gmail.com"
Nethra@LAPTOP-JR9FSSG9 MINGW64 ~/git (master)
$  git config --global user.name "rameshgit12"

Verify the status 
git status
showing red color for untracking files
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        readme.txt
nothing added to commit but untracked files present (use "git add" to track)

Move to the staging server
git add readme.txt
it is moved to the staging server

Verify the status again
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
        modified:   readme.txt
no changes added to commit (use "git add" and/or "git commit -a")

Commiting the changes
git commit  ==> commiting the staging server

git commit -m "change 3"
m means that message

Verify the history of changes whoever commit the changes
git log
$ git log
commit e6a27850fbc122dce1bc1f774af141aa1647174f (HEAD -> Mybranch, origin/Mybranch, master)
Author: rameshgit12 <rameshexpnet@gmail.com>
Date:   Sun Mar 24 22:54:22 2019 +0530
    message 4 and 5
commit 0a8d7f3830904462fb799f88c00b717f3213dde5
Author: rameshgit12 <rameshexpnet@gmail.com>
Date:   Sun Mar 24 22:49:19 2019 +0530
    latest changes

Added all changes in the staging server:
git add .

We can give like below pattern
git add *.html
touch .gitignore
git add .gitignore

Create your own branch
git branch mybranch
git checkout Mybranch  -->switched to the Mybranch
Nethra@LAPTOP-JR9FSSG9 MINGW64 ~/git (Mybranch)

Push the changes to the GITUB remote repository:
$ git push https://github.com/rameshgit12/Spark.git Mybranch
Enumerating objects: 6, done.
Counting objects: 100% (6/6), done.
Delta compression using up to 8 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (6/6), 533 bytes | 76.00 KiB/s, done.
Total 6 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'Mybranch' on GitHub by visiting:
remote:      https://github.com/rameshgit12/Spark/pull/new/Mybranch
remote:
To https://github.com/rameshgit12/Spark.git
 * [new branch]      Mybranch -> Mybranch



git commit -m 'new updates'

Switch the branch to Master
git checkout master

Merge the Mybranch1 branch to master branch
$ git merge Mybranch1
Updating 951cbec..05e45c4
Fast-forward
 file2 | 0
 file3 | 0
 2 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file2
 create mode 100644 file3

Eg.,
git commit -a -m 'change 6'

git remote

git clone url

git remote add origin

cd fluentgard
git remote -v
git fetch origin
Nethra@LAPTOP-JR9FSSG9 MINGW64 ~/git (Mybranch)

Pull the GITUB remote changes into our local
$ git pull origin master
From https://github.com/rameshgit12/Spark
 * branch            master     -> FETCH_HEAD
fatal: refusing to merge unrelated histories
Nethra@LAPTOP-JR9FSSG9 MINGW64 ~/git (Mybranch)
$ git pull origin Mybranch
From https://github.com/rameshgit12/Spark
 * branch            Mybranch   -> FETCH_HEAD
Already up to date.

Delete some files in GITUB and pull it again, Now we can match the datas between local and remote GITUB

git push origin master  
$ git push origin master -f
Enumerating objects: 14, done.
Counting objects: 100% (14/14), done.
Delta compression using up to 8 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (10/10), 802 bytes | 89.00 KiB/s, done.
Total 10 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), done.
To https://github.com/rameshgit12/Spark.git
 + b4c67eb...951cbec master -> master (forced update)







Thursday, March 21, 2019

Scala Functions Examples

Aggregation
def aggregate[B](z: =>B)(seqop: (B, A) => B, combop: (B, B) => B): B = foldLeft(z)(seqop)

scala> println("Step 1: How to initialize a Set of type String to represent Donut elements")
Step 1: How to initialize a Set of type String to represent Donut elements

scala> val donutBasket1: Set[String] = Set("Plain Donut", "Strawberry Donut")
donutBasket1: Set[String] = Set(Plain Donut, Strawberry Donut)

scala> println(s"Elements of donutBasket1 = $donutBasket1")
Elements of donutBasket1 = Set(Plain Donut, Strawberry Donut)

scala> val donutLengthAccumulator: (Int, String) => Int = (accumulator, donutName) => accumulator + donutName.length
donutLengthAccumulator: (Int, String) => Int = <function2>
scala>

scala> println("\nStep 3: How to call aggregate function with the accumulator function from Step 2")
Step 3: How to call aggregate function with the accumulator function from Step 2

scala> val totalLength = donutBasket1.aggregate(0)(donutLengthAccumulator, _ + _)
totalLength: Int = 27

scala> println(s"Total length of elements in donutBasket1 = $totalLength")
Total length of elements in donutBasket1 = 27
scala>

scala> println("\nStep 4: How to initialize a Set of Tuple3 elements to represent Donut name, price and quantity")
Step 4: How to initialize a Set of Tuple3 elements to represent Donut name, price and quantity

scala> val donutBasket2: Set[(String, Double, Int)] = Set(("Plain Donut", 1.50, 10), ("Strawberry Donut", 2.0, 10))
donutBasket2: Set[(String, Double, Int)] = Set((Plain Donut,1.5,10), (Strawberry Donut,2.0,10))

scala> println(s"Elements of donutBasket2 = $donutBasket2")
Elements of donutBasket2 = Set((Plain Donut,1.5,10), (Strawberry Donut,2.0,10))

Step 5: How to define an accumulator function to calculate the total cost of Donuts

scala> val totalCostAccumulator: (Double, Double, Int) => Double = (accumulator, price, quantity) => accumulator + (price * quantity)
totalCostAccumulator: (Double, Double, Int) => Double = <function3>

scala> println("\nStep 6: How to call aggregate function with accumulator function from Step 5")
Step 6: How to call aggregate function with accumulator function from Step 5

scala> val totalCost = donutBasket2.aggregate(0.0)((accumulator: Double, tuple: (String, Double, Int)) => totalCostAccumulator(accumulator, tuple._2, tuple._3), _ + _)
totalCost: Double = 35.0

scala> println(s"Total cost of donuts in donutBasket2 = $totalCost")
Total cost of donuts in donutBasket2 = 35.0

Collect:
def collect[B](pf: PartialFunction[A, B]): Traversable[B]

Step 1: How to initialize a Sequence which contains donut names and prices
scala> val donutNamesandPrices: Seq[Any] = Seq("Plain Donut", 1.5, "Strawberry Donut", 2.0, "Glazed Donut", 2.5)
donutNamesandPrices: Seq[Any] = List(Plain Donut, 1.5, Strawberry Donut, 2.0, Glazed Donut, 2.5)

scala> println(s"Elements of donutNamesAndPrices = $donutNamesandPrices")
Elements of donutNamesAndPrices = List(Plain Donut, 1.5, Strawberry Donut, 2.0, Glazed Donut, 2.5)

scala> println("\nStep 2: How to use collect function to cherry pick all the donut names")
Step 2: How to use collect function to cherry pick all the donut names

scala> val donutNames: Seq[String] = donutNamesandPrices.collect{ case name: String => name }
donutNames: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 3: How to use collect function to cherry pick all the donut prices")
Step 3: How to use collect function to cherry pick all the donut prices

scala> val donutPrices: Seq[Double] = donutNamesandPrices.collect{ case price: Double => price }
donutPrices: Seq[Double] = List(1.5, 2.0, 2.5)

scala> println(s"Elements of donutPrices = $donutPrices")
Elements of donutPrices = List(1.5, 2.0, 2.5)


Diff:
def diff(that: GenSet[A]): This

scala> println("Step 1: How to initialize a Set containing 3 donuts")
Step 1: How to initialize a Set containing 3 donuts

scala> val donutBasket1: Set[String] = Set("Plain Donut", "Strawberry Donut", "Glazed Donut")
donutBasket1: Set[String] = Set(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donutBasket1 = $donutBasket1")
Elements of donutBasket1 = Set(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 2: How to initialize a Set containing 2 donuts")
Step 2: How to initialize a Set containing 2 donuts

scala> val donutBasket2: Set[String] = Set("Glazed Donut", "Vanilla Donut")
donutBasket2: Set[String] = Set(Glazed Donut, Vanilla Donut)

scala> println(s"Elements of donutBasket2 = $donutBasket2")
Elements of donutBasket2 = Set(Glazed Donut, Vanilla Donut)

scala> println("\nStep 3: How to find the difference between two Sets using the diff function")
Step 3: How to find the difference between two Sets using the diff function

scala> val diffDonutBasket1From2: Set[String] = donutBasket1 diff donutBasket2
diffDonutBasket1From2: Set[String] = Set(Plain Donut, Strawberry Donut)

scala> println(s"Elements of diffDonutBasket1From2 = $diffDonutBasket1From2")
Elements of diffDonutBasket1From2 = Set(Plain Donut, Strawberry Donut)

scala> println("\nStep 4: How to find the difference between two Sets using the diff function")
Step 4: How to find the difference between two Sets using the diff function

scala> val diffDonutBasket2From1: Set[String] = donutBasket2 diff donutBasket1
diffDonutBasket2From1: Set[String] = Set(Vanilla Donut)

scala> println(s"Elements of diff DonutBasket2From1 = $diffDonutBasket2From1")
Elements of diff DonutBasket2From1 = Set(Vanilla Donut)
scala>

scala> println("\nStep 5: How to find the difference between two Sets using the --")
Step 5: How to find the difference between two Sets using the --

scala> println(s"Difference between donutBasket1 and donutBasket2 = ${donutBasket1 -- donutBasket2}")

Difference between donutBasket1 and donutBasket2 = Set(Plain Donut, Strawberry Donut)
scala> println(s"Difference between donutBasket2 and donutBasket1 = ${donutBasket2 -- donutBasket1}")
Difference between donutBasket2 and donutBasket1 = Set(Vanilla Donut)

DROP:
def drop(n: Int): Repr
scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
donuts: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donuts = $donuts")
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 2: How to drop the first element using drop function")
Step 2: How to drop the first element using drop function

scala> println(s"Drop the first element in the sequence = ${donuts.drop(1)}")
Drop the first element in the sequence = List(Strawberry Donut, Glazed Donut)

scala> println("\nStep 3: How to drop the first two elements using the drop function")
Step 3: How to drop the first two elements using the drop function

scala> println(s"Drop the first and second elements in the sequence = ${donuts.drop(2)}")
Drop the first and second elements in the sequence = List(Glazed Donut)

DropWhile
def dropWhile(p: (A) ⇒ Boolean): Repr

scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
donuts: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donuts = $donuts")
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 2: How to drop elements from the sequence using the dropWhile function")
Step 2: How to drop elements from the sequence using the dropWhile function

scala> println(s"Drop donut elements whose name starts with letter P = ${donuts.dropWhile(_.charAt(0) == 'P')}")
Drop donut elements whose name starts with letter P = List(Strawberry Donut, Glazed Donut)
scala> val dropElementsPredicate: (String) => Boolean = (donutName) => donutName.charAt(0) == 'P'
dropElementsPredicate: String => Boolean = <function1>

scala> println(s"Value function dropElementsPredicate = $dropElementsPredicate")
Value function dropElementsPredicate = <function1>
scala>

scala> println("\nStep 4: How to drop elements using the predicate function from Step 3")
Step 4: How to drop elements using the predicate function from Step 3

scala> println(s"Drop elements using function from Step 3 = ${donuts.dropWhile(dropElementsPredicate)}")
Drop elements using function from Step 3 = List(Strawberry Donut, Glazed Donut)

Exists:

scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
donuts: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donuts = $donuts")
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
scala>

scala> println("\nStep 2: How to check if a particular element exists in the sequence using the exists function")
Step 2: How to check if a particular element exists in the sequence using the exists function

scala> val doesPlainDonutExists: Boolean = donuts.exists(donutName => donutName == "Plain Donut")
doesPlainDonutExists: Boolean = true

scala> println(s"Does Plain Donut exists = $doesPlainDonutExists")
Does Plain Donut exists = true

scala> val doesPlainDonutExists: Boolean = donuts.exists(donutName => (donutName == "Plain Donut") || (donutName == "Glazed Donut"))
doesPlainDonutExists: Boolean = true

scala> println("\nStep 3: How to declare a predicate value function for the exists function")
Step 3: How to declare a predicate value function for the exists function

scala> val plainDonutPredicate: (String) => Boolean = (donutName) => donutName == "Plain Donut"
plainDonutPredicate: String => Boolean = <function1>

scala> println(s"Value function plainDonutPredicate = $plainDonutPredicate")
Value function plainDonutPredicate = <function1>

scala> println("\nStep 4: How to find element Plain Donut using the exists function and passing through the predicate function from Step 3")
Step 4: How to find element Plain Donut using the exists function and passing through the predicate function from Step 3

scala> println(s"Does Plain Donut exists = ${donuts.exists(plainDonutPredicate)}")
Does Plain Donut exists = true

scala> println("\nStep 5: How to declare a predicate def function for the exists function")
Step 5: How to declare a predicate def function for the exists function

scala> def plainDonutPredicateFunction(donutName: String): Boolean = donutName == "Plain Donut"
plainDonutPredicateFunction: (donutName: String)Boolean
scala>
scala> println("\nStep 6: How to find element Plain Donut using the exists function and passing through the predicate function from Step 5")
Step 6: How to find element Plain Donut using the exists function and passing through the predicate function from Step 5

scala> println(s"Does plain Donut exists = ${donuts.exists(plainDonutPredicateFunction(_))}")
Does plain Donut exists = true

filter and filterNot
def filter(p: (A) ⇒ Boolean): Repr
def filterNot(p: (A) ⇒ Boolean): Repr
scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut", "Vanilla Donut")
donuts: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut, Vanilla Donut)
scala> println(s"Elements of donuts = $donuts")

Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut, Vanilla Donut)

scala> println("\nStep 2: How to keep only Plain and Glazed Donuts using the filter method")
Step 2: How to keep only Plain and Glazed Donuts using the filter method

scala> val sequenceWithPlainAndGlazedDonut = donuts.filter { donutName =>
     |   donutName.contains("Plain") || donutName.contains("Glazed")
     | }
sequenceWithPlainAndGlazedDonut: Seq[String] = List(Plain Donut, Glazed Donut)

scala> println(s"Sequence with Plain and Glazed donuts only = $sequenceWithPlainAndGlazedDonut")

Sequence with Plain and Glazed donuts only = List(Plain Donut, Glazed Donut)
scala>

scala> println("\nStep 3: How to filter out element Vanilla Donut using the filterNot function")
Step 3: How to filter out element Vanilla Donut using the filterNot function

scala> val sequenceWithoutVanillaDonut = donuts.filterNot(donutName => donutName == "Vanilla Donut" )
sequenceWithoutVanillaDonut: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Sequence without vanilla donut = $sequenceWithoutVanillaDonut")
Sequence without vanilla donut = List(Plain Donut, Strawberry Donut, Glazed Donut)

find:
def find(p: (A) ⇒ Boolean): Option[A]
scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
donuts: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donuts = $donuts")
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 2: How to find a particular element in the sequence using the find function")
Step 2: How to find a particular element in the sequence using the find function

scala> val plainDonut: Option[String] = donuts.find(donutName => donutName == "Plain Donut")
plainDonut: Option[String] = Some(Plain Donut)

scala> println(s"Find Plain Donut = ${plainDonut.get}")
Find Plain Donut = Plain Donut

scala> println("\nStep 3: How to find element Vanilla Donut which does not exist in the sequence using the find function")
Step 3: How to find element Vanilla Donut which does not exist in the sequence using the find function

scala> val vanillaDonut: String = donuts.find(_ == "Vanilla Donut").get
java.util.NoSuchElementException: None.get
  at scala.None$.get(Option.scala:347)
  at scala.None$.get(Option.scala:345)
  ... 32 elided

scala> println(s"Find Vanilla Donuts = $vanillaDonut")
<console>:12: error: not found: value vanillaDonut
       println(s"Find Vanilla Donuts = $vanillaDonut")
   
scala> println("\nStep 4: How to find element Vanilla Donut using the find function and getOrElse")
Step 4: How to find element Vanilla Donut using the find function and getOrElse

scala> val vanillaDonut2: String = donuts.find(_ == "Vanilla Donut").getOrElse("Vanilla Donut was not found!")
vanillaDonut2: String = Vanilla Donut was not found!

scala> println(s"Find Vanilla Donuts = $vanillaDonut2")
Find Vanilla Donuts = Vanilla Donut was not found!

flatMap:
def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): TraversableOnce[B]
scala> println("\nStep 3: How to find element Vanilla Donut which does not exist in the sequence using the find 

scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts1: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
donuts1: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donuts1 = $donuts1")
Elements of donuts1 = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 2: How to initialize another Sequence of donuts")
Step 2: How to initialize another Sequence of donuts

scala> val donuts2: Seq[String] = Seq("Vanilla Donut", "Glazed Donut")
donuts2: Seq[String] = List(Vanilla Donut, Glazed Donut)

scala> println(s"Elements of donuts2 = $donuts2")
Elements of donuts2 = List(Vanilla Donut, Glazed Donut)

scala> println("\nStep 3: How to create a List of donuts initialized using the two Sequences from Step 1 and Step 2")
Step 3: How to create a List of donuts initialized using the two Sequences from Step 1 and Step 2

scala> val listDonuts: List[Seq[String]] = List(donuts1, donuts2)
listDonuts: List[Seq[String]] = List(List(Plain Donut, Strawberry Donut, Glazed Donut), List(Vanilla Donut, Glazed Donut))

scala> println(s"Elements of listDonuts = $listDonuts")
Elements of listDonuts = List(List(Plain Donut, Strawberry Donut, Glazed Donut), List(Vanilla Donut, Glazed Donut))

scala>
scala> println("\nStep 4: How to return a single list of donut using the flatMap function")
Step 4: How to return a single list of donut using the flatMap function

scala> val listDonutsFromFlatMap: List[String] = listDonuts.flatMap(seq => seq)
listDonutsFromFlatMap: List[String] = List(Plain Donut, Strawberry Donut, Glazed Donut, Vanilla Donut, Glazed Donut)

scala> println(s"Elements of listDonutsFromFlatMap as a flatMap as a single list = $listDonutsFromFlatMap")
Elements of listDonutsFromFlatMap as a flatMap as a single list = List(Plain Donut, Strawberry Donut, Glazed Donut, Vanilla Donut, Glazed Donut)
scala>

Flatten:
def flatten[B]: Traversable[B]

ala> println("\nStep 3: How to find element Vanilla Donut which does not exist in the sequence using the find 

scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts1: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
donuts1: Seq[String] = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println(s"Elements of donuts1 = $donuts1")
Elements of donuts1 = List(Plain Donut, Strawberry Donut, Glazed Donut)

scala> println("\nStep 2: How to initialize another Sequence of donuts")
Step 2: How to initialize another Sequence of donuts

scala> val donuts2: Seq[String] = Seq("Vanilla Donut", "Glazed Donut")
donuts2: Seq[String] = List(Vanilla Donut, Glazed Donut)

scala> println(s"Elements of donuts2 = $donuts2")
Elements of donuts2 = List(Vanilla Donut, Glazed Donut)

scala> println("\nStep 3: How to create a List of donuts initialized using the two Sequences from Step 1 and Step 2")

Step 3: How to create a List of donuts initialized using the two Sequences from Step 1 and Step 2
scala> val listDonuts: List[Seq[String]] = List(donuts1, donuts2)
listDonuts: List[Seq[String]] = List(List(Plain Donut, Strawberry Donut, Glazed Donut), List(Vanilla Donut, Glaz

scala> println("Step 1: How to initialize a Sequence of donuts")
Step 1: How to initialize a Sequence of donuts

scala> val donuts1: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
donuts1: Seq[String] = List(Plain, Strawberry, Glazed)

scala> println(s"Elements of donuts1 = $donuts1")
Elements of donuts1 = List(Plain, Strawberry, Glazed)
scala>
scala> println("\nStep 2: How to initialize another Sequence of donuts")
Step 2: How to initialize another Sequence of donuts
scala> val donuts2: Seq[String] = Seq("Vanilla", "Glazed")

donuts2: Seq[String] = List(Vanilla, Glazed)
scala> println(s"Elements of donuts2 = $donuts2")
Elements of donuts2 = List(Vanilla, Glazed)
scala>
scala> println("\nStep 3: How to create a List of donuts initialized using the two Sequences from Step 1 and Step 2")
Step 3: How to create a List of donuts initialized using the two Sequences from Step 1 and Step 2

scala> val listDonuts: List[Seq[String]] = List(donuts1, donuts2)
listDonuts: List[Seq[String]] = List(List(Plain, Strawberry, Glazed), List(Vanilla, Glazed))

scala> println(s"Elements of listDonuts = $listDonuts")
Elements of listDonuts = List(List(Plain, Strawberry, Glazed), List(Vanilla, Glazed))

scala> println("\nStep 4: How to return a single list of donut using the flatten function")
Step 4: How to return a single list of donut using the flatten function

scala> val listDonutsFromFlatten: List[String] = listDonuts.flatten
listDonutsFromFlatten: List[String] = List(Plain, Strawberry, Glazed, Vanilla, Glazed)

scala> println(s"Elements of listDonutsFromFlatten = $listDonutsFromFlatten")
Elements of listDonutsFromFlatten = List(Plain, Strawberry, Glazed, Vanilla, Glazed)

scala> println("\nStep 5: How to append the word Donut to each element of listDonuts using flatten and map functions")
Step 5: How to append the word Donut to each element of listDonuts using flatten and map functions

scala> val listDonutsFromFlatten2: List[String] = listDonuts.flatten.map(_ + " Donut")
listDonutsFromFlatten2: List[String] = List(Plain Donut, Strawberry Donut, Glazed Donut, Vanilla Donut, Glazed Donut)

scala> println(s"Elements of listDonutsFromFlatten2 = $listDonutsFromFlatten2")
Elements of listDonutsFromFlatten2 = List(Plain Donut, Strawberry Donut, Glazed Donut, Vanilla Donut, Glazed Donut)

Fold:

def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1

// Start writing your ScalaFiddle code here

println("Step 1: How to initialize a sequence of donut prices")
val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Donut prices = $prices")

println("\nStep 2: How to sum all the donut prices using fold function")
val sum = prices.fold(0.0)(_ + _)
println(s"Sum = $sum")

println("\nStep 3: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donuts1 = $donuts")

println("\nStep 4: How to create a String of all donuts using fold function")
println(s"All donuts = ${donuts.fold("")((acc, s) => acc + s + " Donut ")}")

println("\nStep 5: How to declare a value function to create the donut string")
val concatDonuts: (String, String) => String = (s1, s2) => s1 + s2 + " Donut "
println(s"Value function concatDonuts = $concatDonuts")

println("\nStep 6: How to create a String of all donuts using value function from Step 5 and fold function")
println(s"All donuts = ${donuts.fold("")(concatDonuts)}") 
Output
Step 1: How to initialize a sequence of donut prices Donut prices = List(1.5, 2, 2.5)

Step 2: How to sum all the donut prices using fold function Sum = 6

Step 3: How to initialize a Sequence of donuts Elements of donuts1 = List(Plain, Strawberry, Glazed)

Step 4: How to create a String of all donuts using fold function All donuts = Plain Donut Strawberry Donut Glazed Donut 

Step 5: How to declare a value function to create the donut string Value function concatDonuts = <function2>

Step 6: How to create a String of all donuts using value function from Step 5 and fold function All donuts = Plain Donut Strawberry Donut Glazed Donut 

foldLeft:
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B 

println("Step 1: How to initialize a sequence of donut prices")
val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Donut prices = $prices")

println("\nStep 2: How to sum all the donut prices using foldLeft function")
val sum = prices.foldLeft(0.0)(_ + _)
println(s"Sum = $sum")

println("\nStep 3: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donuts1 = $donuts")

println("\nStep 4: How to create a String of all donuts using foldLeft function")
println(s"All donuts = ${donuts.foldLeft("")((a, b) => a + b + " Donut ")}")

println("\nStep 5: How to declare a value function to create the donut string")
val concatDonuts: (String, String) => String = (a, b) => a + b + " Donut "
println(s"Value function concatDonuts = $concatDonuts")

println("\nStep 6: How to create a String of all donuts using value function from Step 5 and foldLeft function")
println(s"All donuts = ${donuts.foldLeft("")(concatDonuts)}") 

Output
Step 1: How to initialize a sequence of donut prices Donut prices = List(1.5, 2, 2.5)

Step 2: How to sum all the donut prices using foldLeft function Sum = 6

Step 3: How to initialize a Sequence of donuts Elements of donuts1 = List(Plain, Strawberry, Glazed)

Step 4: How to create a String of all donuts using foldLeft function All donuts = Plain Donut Strawberry Donut Glazed Donut 

Step 5: How to declare a value function to create the donut string Value function concatDonuts = <function2>

Step 6: How to create a String of all donuts using value function from Step 5 and foldLeft function All donuts = Plain Donut Strawberry Donut Glazed Donut 


FoldRight:
def foldRight[B](z: B)(op: (A, B) ⇒ B): B 

println("Step 1: How to initialize a sequence of donut prices")
val prices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Donut prices = $prices")

println("\nStep 2: How to sum all the donut prices using foldRight function")
val sum = prices.foldRight(0.0)(_ + _)
println(s"Sum = $sum")

println("\nStep 3: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donuts1 = $donuts")

println("\nStep 4: How to create a String of all donuts using foldRight function")
println(s"All donuts = ${donuts.foldRight("")((a, b) => a + " Donut " + b)}")


println("\nStep 5: How to declare a value function to create the donut string")
val concatDonuts: (String, String) => String = (a, b) => a + " Donut " + b
println(s"Value function concatDonuts = $concatDonuts")

println("\nStep 6: How to create a String of all donuts using value function from Step 5 and foldRight function")
println(s"All donuts = ${donuts.foldRight("")(concatDonuts)}") 

Output

Step 1: How to initialize a sequence of donut prices Donut prices = List(1.5, 2, 2.5)

Step 2: How to sum all the donut prices using foldRight function Sum = 6

Step 3: How to initialize a Sequence of donuts Elements of donuts1 = List(Plain, Strawberry, Glazed)

Step 4: How to create a String of all donuts using foldRight function All donuts = Plain Donut Strawberry Donut Glazed Donut 
 Step 5: How to declare a value function to create the donut string Value function concatDonuts = <function2>

Step 6: How to create a String of all donuts using value function from Step 5 and foldRight function All donuts = Plain Donut Strawberry Donut Glazed Donut 


foreach:
def foreach(f: (A) ⇒ Unit): Unit

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to loop through all the elements in the sequence using the foreach function")
donuts.foreach(println(_))

println("\nStep 3: How to loop through and access all the elements in the sequence using the foreach function")
donuts.foreach(donutName => println(s"donutName = $donutName"))

println("\nStep 4: How to declare a value function to format a donut names into upper case format")
val uppercase: (String) => String = (s) => {
 val upper = s.toUpperCase
 println(upper)
 upper
}
println(s"Value function formatting donut names to uppercase = $uppercase")

println("\nStep 5: How to format all donuts to uppercase using value function from Step 4")
donuts.foreach(uppercase) 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to loop through all the elements in the sequence using the foreach function Plain Donut Strawberry Donut Glazed Donut

Step 3: How to loop through and access all the elements in the sequence using the foreach function donutName = Plain Donut donutName = Strawberry Donut donutName = Glazed Donut

Step 4: How to declare a value function to format a donut names into upper case format Value function formatting donut names to uppercase = <function1>

Step 5: How to format all donuts to uppercase using value function from Step 4 PLAIN DONUT STRAWBERRY DONUT GLAZED DONUT


groupBy:
groupBy[K](f: (A) ⇒ K): immutable.Map[K, Repr] 

// Start writing your ScalaFiddle code here
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to group elements in a sequence using the groupBy function")
val donutsGroup: Map[Char, Seq[String]] = donuts.groupBy(_.charAt(0))
println(s"Group elements in the donut sequence by the first letter of the donut name = $donutsGroup")


println("\nStep 3: How to create a case class to represent Donut objects")
case class Donut(name: String, price: Double)

println("\nStep 4: How to create a Sequence of type Donut")
val donuts2: Seq[Donut] = Seq(Donut("Plain Donut", 1.5), Donut("Strawberry Donut", 2.0), Donut("Glazed Donut", 2.5))
println(s"Elements of donuts2 = $donuts2")

println(s"\nStep 5: How to group case classes donut objects by the name property")
val donutsGroup2: Map[String, Seq[Donut]] = donuts2.groupBy(_.name)
println(s"Group element in the sequence of type Donut grouped by the donut name = $donutsGroup2") 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to group elements in a sequence using the groupBy function Group elements in the donut sequence by the first letter of the donut name = Map(S -> List(Strawberry Donut), G -> List(Glazed Donut), P -> List(Plain Donut))

Step 3: How to create a case class to represent Donut objects

Step 4: How to create a Sequence of type Donut Elements of donuts2 = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))

Step 5: How to group case classes donut objects by the name property Group element in the sequence of type Donut grouped by the donut name = Map(Glazed Donut -> List(Donut(Glazed Donut,2.5)), Plain Donut -> List(Donut(Plain Donut,1.5)), Strawberry Donut -> List(Donut(Strawberry Donut,2)))

Head:
def head: A 

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to access the first element of the donut sequence")
println(s"First element of donut sequence = ${donuts(0)}")

println("\nStep 3: How to access the first element of the donut sequence using the head method")
println(s"First element of donut sequence using head method = ${donuts.head}")

println("\nStep 4: How to create an empty sequence")
val donuts2: Seq[String] = Seq.empty[String]
println(s"Elements of donuts2 = $donuts2")

println("\nStep 5: How to access the first element of the donut sequence using the headOption function")
println(s"First element of empty sequence = ${donuts2.headOption.getOrElse("No donut was found!")}") 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to access the first element of the donut sequence First element of donut sequence = Plain Donut

Step 3: How to access the first element of the donut sequence using the head method First element of donut sequence using head method = Plain Donut

Step 4: How to create an empty sequence Elements of donuts2 = List()

Step 5: How to access the first element of the donut sequence using the headOption function First element of empty sequence = No donut was found!

IsEmpty
abstract def isEmpty: Boolean

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to find out if a sequence is empty using isEmpty function")
println(s"Is donuts sequence empty = ${donuts.isEmpty}")

println("\nStep 3: How to create an empty sequence")
val donuts2: Seq[String] = Seq.empty[String]
println(s"Elements of donuts2 = $donuts2")

println("\nStep 4: How to find out if a sequence is empty using isEmpty function")
println(s"Is donuts2 sequence empty = ${donuts2.isEmpty}") 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to find out if a sequence is empty using isEmpty function Is donuts sequence empty = false

Step 3: How to create an empty sequence Elements of donuts2 = List()

Step 4: How to find out if a sequence is empty using isEmpty function Is donuts2 sequence empty = true

Intersect function
def intersect(that: GenSet[A]): Repr
// Start writing your ScalaFiddle code here
println("Step 1: How to initialize a Set of donuts")
val donuts1: Set[String] = Set("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts1 = $donuts1")

println("\nStep 2: How to initialize another Set of donuts")
val donuts2: Set[String] = Set("Plain Donut", "Chocolate Donut", "Vanilla Donut")
println(s"Elements of donuts2 = $donuts2")

println("\nStep 3: How to find the common elements between two Sets using intersect function")
println(s"Common elements between donuts1 and donuts2 = ${donuts1 intersect donuts2}")
println(s"Common elements between donuts2 and donuts1 = ${donuts2 intersect donuts1}")

println("\nStep 4: How to find the common elements between two Sets using & function")
println(s"Common elements between donuts1 and donuts2 = ${donuts1 & donuts2}")
println(s"Common elements between donuts2 and donuts1 = ${donuts2 & donuts1}")

Output
Step 1: How to initialize a Set of donuts Elements of donuts1 = Set(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to initialize another Set of donuts Elements of donuts2 = Set(Plain Donut, Chocolate Donut, Vanilla Donut)

Step 3: How to find the common elements between two Sets using intersect function Common elements between donuts1 and donuts2 = Set(Plain Donut) Common elements between donuts2 and donuts1 = Set(Plain Donut)

Step 4: How to find the common elements between two Sets using & function Common elements between donuts1 and donuts2 = Set(Plain Donut) Common elements between donuts2 and donuts1 = Set(Plain Donut)

Last:
def last: A

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")


println("\nStep 2: How to access the last element of the donut sequence by index")
println(s"Last element of donut sequence = ${donuts(donuts.size - 1)}")


println("\nStep 3: How to access the last element of the donut sequence by using the last function")
println(s"Last element of donut sequence = ${donuts.last}")

println("\nStep 4: How to create an empty sequence")
val donuts2: Seq[String] = Seq.empty[String]
println(s"Elements of donuts2 = $donuts2")

println("\nStep 5: How to access the last element of the donut sequence using the lastOption function")
println(s"Last element of empty sequence = ${donuts2.lastOption.getOrElse("No donut was found!")}") 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to access the last element of the donut sequence by index Last element of donut sequence = Glazed Donut

Step 3: How to access the last element of the donut sequence by using the last function Last element of donut sequence = Glazed Donut
 Step 4: How to create an empty sequence Elements of donuts2 = List()

Step 5: How to access the last element of the donut sequence using the lastOption function Last element of empty sequence = No donut was found!

Map:
def map[B](f: (A) ⇒ B): Traversable[B]

println("Step 1: How to initialize a Sequence of donuts")
val donuts1: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donuts1 = $donuts1")

println("\nStep 2: How to append the word Donut to each element using the map function")
val donuts2: Seq[String] = donuts1.map(_+ " Donut")
println(s"Elements of donuts2 = $donuts2")

println("\nStep 3: How to create a donut sequence with one None element")
val donuts3: Seq[AnyRef] = Seq("Plain", "Strawberry", None)
donuts3.foreach(println(_))

println("\nStep 4: How to filter out the None element using map function")
val donuts4: Seq[String] = donuts3.map {
 case donut: String => donut + " Donut"
 case None => "Unknown Donut"
}
println(s"Elements of donuts4 = $donuts4")

println("\nStep 5: How to define couple of functions which returns an Option of type String")
def favoriteDonut: Option[String] = Some("Glazed Donut")

def leastFavoriteDonut: Option[String] = None

println("\nStep 6: How to use map function to filter out None values")
favoriteDonut.map(donut => println(s"Favorite donut = $donut"))
leastFavoriteDonut.map(donut=> println(s"Least favorite donut = $donut"))

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts1 = List(Plain, Strawberry, Glazed)

Step 2: How to append the word Donut to each element using the map function Elements of donuts2 = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 3: How to create a donut sequence with one None element Plain Strawberry None

Step 4: How to filter out the None element using map function Elements of donuts4 = List(Plain Donut, Strawberry Donut, Unknown Donut)

Step 5: How to define couple of functions which returns an Option of type String

Step 6: How to use map function to filter out None values Favorite donut = Glazed Donut

Max function:
def max: A 

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to find the maximum element in the sequence using the max
function")
println(s"Max element in the donuts sequence = ${donuts.max}")

println("\nStep 3: How to initialize donut prices")
val prices: Seq[Double] = Seq(1.50, 2.0, 2.50)
println(s"Elements of prices = $prices")

println("\nStep 4: How to find the maximum element in the sequence using the max function")
println(s"Max element in the donut prices sequence = ${prices.max}")

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to find the maximum element in the sequence using the max function Max element in the donuts sequence = Strawberry Donut

Step 3: How to initialize donut prices Elements of prices = List(1.5, 2, 2.5)

Step 4: How to find the maximum element in the sequence using the max function Max element in the donut prices sequence = 2.5

MaxBy:
def maxBy[B](f: (A) ⇒ B): A 

println("Step 1: How to create a case class to represent Donut object")
case class Donut(name: String, price: Double)

println("\nStep 2: How to create a Sequence of type Donut")
val donuts: Seq[Donut] = Seq(Donut("Plain Donut", 1.5), Donut("Strawberry Donut", 2.0), Donut("Glazed Donut", 2.5))
println(s"Elements of donuts = $donuts")

println("\nStep 3: How to find the maximum element in a sequence of case classes objects using the maxBy function")
println(s"Maximum element in sequence of case class of type Donut, ordered by price = ${donuts.maxBy(donut => donut.price)}")

println("\nStep 4: How to declare a value predicate function for maxBy function")
val donutsMaxBy: (Donut) => Double = (donut) => donut.price
println(s"Value function donutMaxBy = $donutsMaxBy")

println("\nStep 5: How to find the maximum element using maxBy function and pass through the predicate function from Step 4")
println(s"Maximum element in sequence using function from Step 3 = ${donuts.maxBy(donutsMaxBy)}")

Output
Step 1: How to create a case class to represent Donut object

Step 2: How to create a Sequence of type Donut Elements of donuts = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))

Step 3: How to find the maximum element in a sequence of case classes objects using the maxBy function Maximum element in sequence of case class of type Donut, ordered by price = Donut(Glazed Donut,2.5)

Step 4: How to declare a value predicate function for maxBy function Value function donutMaxBy = <function1>

Step 5: How to find the maximum element using maxBy function and pass through the predicate function from Step 4 Maximum element in sequence using function from Step 3 = Donut(Glazed Donut,2.5)

Min:
def min: A
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to find the minimum element in the sequence using the min function")
println(s"Min element in the donuts sequence = ${donuts.min}")

println("\nStep 3: How to initialize a Sequence of donut prices")
val prices: Seq[Double] = Seq(1.50, 2.0, 2.50)
println(s"Elements of prices = $prices")

println("\nStep 4: How to find the minimum element in the sequence using the min function")
println(s"Min element in the donut prices sequence = ${prices.min}")

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to find the minimum element in the sequence using the min function")
println(s"Min element in the donuts sequence = ${donuts.min}")

println("\nStep 3: How to initialize a Sequence of donut prices")
val prices: Seq[Double] = Seq(1.50, 2.0, 2.50)
println(s"Elements of prices = $prices")

println("\nStep 4: How to find the minimum element in the sequence using the min function")
println(s"Min element in the donut prices sequence = ${prices.min}")

output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to find the minimum element in the sequence using the min function Min element in the donuts sequence = Glazed Donut

Step 3: How to initialize a Sequence of donut prices Elements of prices = List(1.5, 2, 2.5)

Step 4: How to find the minimum element in the sequence using the min function Min element in the donut prices sequence = 1.5

MinBy:
def minBy[B](f: (A) ⇒ B): A

// Start writing your ScalaFiddle code here
println("Step 1: How to create case class to represent Donut object")
case class Donut(name: String, price: Double)

println("\nStep 2: How to create a Sequence of type Donut")
val donuts: Seq[Donut] = Seq(Donut("Plain Donut", 1.5), Donut("Strawberry Donut", 2.0), Donut("Glazed Donut", 2.5))
println(s"Elements of donuts = $donuts")

println("\nStep 3: How to find the minimum element in a sequence of case classes using the minBy function")
println(s"Minimum element in sequence of case class of type Donut, ordered by price = ${donuts.minBy(donut => donut.price)}")

println("\nStep 4: How to declare a value predicate function for minBy function")
val donutsMinBy: (Donut) => Double = (donut) => donut.price
println(s"Value function donutMinBy = $donutsMinBy")

println("\nStep 5: How to find the minimum element using minBy function and passing through the predicate function from Step 4")
println(s"Minimum element in sequence using function from Step 3 = ${donuts.minBy(donutsMinBy)}")

Output
Step 1: How to create case class to represent Donut object

Step 2: How to create a Sequence of type Donut Elements of donuts = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))

Step 3: How to find the minimum element in a sequence of case classes using the minBy function Minimum element in sequence of case class of type Donut, ordered by price = Donut(Plain Donut,1.5)

Step 4: How to declare a value predicate function for minBy function Value function donutMinBy = <function1>

Step 5: How to find the minimum element using minBy function and passing through the predicate function from Step 4 Minimum element in sequence using function from Step 3 = Donut(Plain Donut,1.5)

Mkstring() 
def mkString: String

def mkString(sep: String): String

def mkString(start: String, sep: String, end: String): String

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to concatenate the elements of a sequence into a String using mkString function")
val donutsAsString: String = donuts.mkString(" and ")
println(s"Donuts elements using mkString function = $donutsAsString")


println("\nStep 3: How to concatenate the elements of a sequence into a String using mkString and specifying prefix and suffix")
val donutsWithPrefixAndSuffix: String = donuts.mkString("My favorite donuts namely ", " and ", " are very tasty!")
println(s"$donutsWithPrefixAndSuffix")

output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to concatenate the elements of a sequence into a String using mkString function Donuts elements using mkString function = Plain Donut and Strawberry Donut and Glazed Donut

Step 3: How to concatenate the elements of a sequence into a String using mkString and specifying prefix and suffix My favorite donuts namely Plain Donut and Strawberry Donut and Glazed Donut are very tasty!


NonEmpty
def nonEmpty: Boolean

// Start writing your ScalaFiddle code here
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to check if a sequence is not empty using nonEmpty function")
println(s"Is donuts sequence NOT empty = ${donuts.nonEmpty}")

println("\nStep 3: How to create an empty sequence")
val emptyDonuts: Seq[String] = Seq.empty[String]
println(s"Elements of emptyDonuts = $emptyDonuts")

println("\nStep 4: How to find out if sequence is empty using nonEmpty function")
println(s"Is emptyDonuts sequence empty = ${emptyDonuts.nonEmpty}")

output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to check if a sequence is not empty using nonEmpty function Is donuts sequence NOT empty = true

Step 3: How to create an empty sequence Elements of emptyDonuts = List()

Step 4: How to find out if sequence is empty using nonEmpty function Is emptyDonuts sequence empty = false

Par:
println("Step 1: How to initialize an Immutable Sequence of various donut flavours")
val donutFlavours: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donutFlavours immutable sequence = $donutFlavours")


println("\nStep 2: Convert the Immutable donut flavours Sequence into Parallel Collection")
import scala.collection.parallel.ParSeq
val donutFlavoursParallel: ParSeq[String] = donutFlavours.par


println("\nStep 3: How to use Scala Parallel Collection")
val donuts: ParSeq[String] = donutFlavoursParallel.map(d => s"$d donut")
println(s"Elements of donuts parallel collection = $donuts")

Scala Parallel Collection
Elements of donuts parallel collection = ParVector(Plain donut, Strawberry donut, Glazed donut)

Partitions:
def partition(p: (A) ⇒ Boolean): (Repr, Repr) 

println("Step 1: How to initialize a sequence which contains donut names and prices")
val donutNamesAndPrices: Seq[Any] = Seq("Plain Donut", 1.5, "Strawberry Donut", 2.0, "Glazed Donut", 2.5)
println(s"Elements of donutNamesAndPrices = $donutNamesAndPrices")


println("\nStep 2: How to split the sequence by the element types using partition function")
val namesAndPrices: (Seq[Any], Seq[Any]) = donutNamesAndPrices.partition {
  case name: String => true
  case price: Double => false
}
println(s"Elements of namesAndPrices = $namesAndPrices")


println("\nStep 3: How to access the donut String sequence from Step 2")
println(s"Donut names = ${namesAndPrices._1}")

val (donutNames, donutPrices) = donutNamesAndPrices.partition {
  case name: String => true
  case _ => false
}
println(s"donutNames = $donutNames")
println(s"donutPrices = $donutPrices")

output
Step 1: How to initialize a sequence which contains donut names and prices Elements of donutNamesAndPrices = List(Plain Donut, 1.5, Strawberry Donut, 2, Glazed Donut, 2.5)

Step 2: How to split the sequence by the element types using partition function Elements of namesAndPrices = (List(Plain Donut, Strawberry Donut, Glazed Donut),List(1.5, 2, 2.5))

Step 3: How to access the donut String sequence from Step 2 Donut names = List(Plain Donut, Strawberry Donut, Glazed Donut) donutNames = List(Plain Donut, Strawberry Donut, Glazed Donut) donutPrices = List(1.5, 2, 2.5)

Reduce:
def reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1 

println("Step 1: How to initialize a sequence of donut prices")
val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donutPrices = $donutPrices")

println("\nStep 2: How to find the sum of the elements using reduce function")
val sum: Double = donutPrices.reduce(_ + _)
println(s"Sum of elements from donutPrices = $sum")

println("\nStep 3: How to find the sum of elements using reduce function explicitly")
val sum1: Double = donutPrices.reduce((a, b) => a + b)
println(s"Sum of elements from donutPrices by calling reduce function explicitly= $sum1")

println("\nStep 4: How to find the cheapest donut using reduce function")
println(s"Cheapest donut price = ${donutPrices.reduce(_ min _)}")


println("\nStep 5: How to find the most expensive donut using reduce function")
println(s"Most expensive donut price = ${donutPrices.reduce(_ max _)}")

println("\nStep 6: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 7: How to concatenate the elements from the sequence using reduce function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduce((left, right) => left + ", " + right)}")

println("\nStep 8: How to declare a value function to concatenate donut names")
val concatDonutNames: (String, String) => String = (left, right) => {
 left + ", " + right
}
println(s"Value function concatDonutNames = $concatDonutNames")

println(s"Elements of donuts sequence concatenated by passing function to the reduce function = ${donuts reduce concatDonutNames}")

println("\nStep 10: How to use option reduce to avoid exception if the collection is empty")
println(s"Using reduce option will NOT throw any exception = ${Seq.empty[String].reduceOption(_ + ", " + _)}")

Output
Step 1: How to initialize a sequence of donut prices Elements of donutPrices = List(1.5, 2, 2.5)

Step 2: How to find the sum of the elements using reduce function Sum of elements from donutPrices = 6

Step 3: How to find the sum of elements using reduce function explicitly Sum of elements from donutPrices by calling reduce function explicitly= 6

Step 4: How to find the cheapest donut using reduce function Cheapest donut price = 1.5

Step 5: How to find the most expensive donut using reduce function Most expensive donut price = 2.5

Step 6: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 7: How to concatenate the elements from the sequence using reduce function Elements of donuts sequence concatenated = Plain Donut, Strawberry Donut, Glazed Donut

Step 8: How to declare a value function to concatenate donut names Value function concatDonutNames = <function2> Elements of donuts sequence concatenated by passing function to the reduce function = Plain Donut, Strawberry Donut, Glazed Donut

Step 10: How to use option reduce to avoid exception if the collection is empty Using reduce option will NOT throw any exception = None

reduceLeft:
def reduceLeft[B >: A](op: (B, A) ⇒ B): B 

println("Step 1: How to initialize a sequence of donut prices")
val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donutPrices = $donutPrices")

println("\nStep 2: How to find the sum of the elements using reduceLeft function")
val sum: Double = donutPrices.reduceLeft(_ + _)
println(s"Sum of elements from donutPrices = $sum")

println("\nStep 3: How to find the sum of elements using reduceLeft function explicitly")
val sum1: Double = donutPrices.reduceLeft((a, b) => a + b)
println(s"Sum of elements from donutPrices by calling reduceLeft function explicitly= $sum1")


println("\nStep 4: How to find the cheapest donut using reduceLeft function")
println(s"Cheapest donut price = ${donutPrices.reduceLeft(_ min _)}")

println("\nStep 5: How to find the most expensive donut using reduceLeft function")
println(s"Most expensive donut price = ${donutPrices.reduceLeft(_ max _)}")

println("\nStep 6: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 7: How to concatenate the elements from the sequence using reduceLeft function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduceLeft((left, right) => left + ", " + right)}")

println("\nStep 8: How to declare a value function to concatenate donut names")
val concatDonutNames: (String, String) => String = (left, right) => {
 left + ", " + right
}
println(s"Value function concatDonutNames = $concatDonutNames")

println("\nStep 9: How to pass a function to reduceLeft function")
println(s"Elements of donuts sequence concatenated by passing function to the reduceLeft function = ${donuts reduceLeft concatDonutNames}")

println("\nStep 10: How to use reduceLeftOption to avoid exception if the collection is empty")
println(s"Using reduceLeftOption will NOT throw any exception = ${Seq.empty[String].reduceLeftOption(_ + ", " + _)}")

Output
Step 1: How to initialize a sequence of donut prices Elements of donutPrices = List(1.5, 2, 2.5)

Step 2: How to find the sum of the elements using reduceLeft function Sum of elements from donutPrices = 6

Step 3: How to find the sum of elements using reduceLeft function explicitly Sum of elements from donutPrices by calling reduceLeft function explicitly= 6

Step 4: How to find the cheapest donut using reduceLeft function Cheapest donut price = 1.5

Step 5: How to find the most expensive donut using reduceLeft function Most expensive donut price = 2.5

Step 6: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 7: How to concatenate the elements from the sequence using reduceLeft function Elements of donuts sequence concatenated = Plain Donut, Strawberry Donut, Glazed Donut

Step 8: How to declare a value function to concatenate donut names Value function concatDonutNames = <function2>

Step 9: How to pass a function to reduceLeft function Elements of donuts sequence concatenated by passing function to the reduceLeft function = Plain Donut, Strawberry Donut, Glazed Donut

Step 10: How to use reduceLeftOption to avoid exception if the collection is empty Using reduceLeftOption will NOT throw any exception = None


ReduceRight:
As per the Scala documentation, the definition of the reduceRight method is as follows: def reduceRight[B >: A](op: (B, A) ⇒ B): B

  def reduceRight[B >: A](op: (A, B) => B): B = {     if (isEmpty)       throw new UnsupportedOperationException("empty.reduceRight")

    reversed.reduceLeft[B]((x, y) => op(y, x))   }

println("Step 1: How to initialize a sequence of donut prices")
val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donutPrices = $donutPrices")

println("\nStep 2: How to find the sum of the elements using reduceRight function")
val sum: Double = donutPrices.reduceRight(_ + _)
println(s"Sum of elements from donutPrices = $sum")

println("\nStep 3: How to find the sum of elements using reduceRight function explicitly")
val sum1: Double = donutPrices.reduceRight((a, b) => a + b)
println(s"Sum of elements from donutPrices by calling reduceRight function explicitly= $sum1")


println("\nStep 4: How to find the cheapest donut using reduceRight function")
println(s"Cheapest donut price = ${donutPrices.reduceRight(_ min _)}")

println(s"Most expensive donut price = ${donutPrices.reduceRight(_ max _)}")

println("\nStep 6: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 7: How to concatenate the elements from the sequence using reduceRight function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduceRight((left, right) => left + ", " + right)}")

println("\nStep 7: How to concatenate the elements from the sequence using reduceRight function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduceRight((left, right) => left + ", " + right)}")

println("\nStep 8: How to declare a value function to concatenate donut names")
val concatDonutNames: (String, String) => String = (left, right) => {
 left + ", " + right
}
println(s"Value function concatDonutNames = $concatDonutNames")

println("\nStep 9: How to pass a function to reduceRight function")
println(s"Elements of donuts sequence concatenated by passing function to the reduceRight function = ${donuts reduceRight concatDonutNames}")

println("\nStep 10: How to use reduceRightOption to avoid exception if the collection is empty")
println(s"Using reduceRightOption will NOT throw any exception = ${Seq.empty[String].reduceRightOption(_ + ", " + _)}")

output
Step 1: How to initialize a sequence of donut prices Elements of donutPrices = List(1.5, 2, 2.5)

Step 2: How to find the sum of the elements using reduceRight function Sum of elements from donutPrices = 6

Step 3: How to find the sum of elements using reduceRight function explicitly Sum of elements from donutPrices by calling reduceRight function explicitly= 6

Step 4: How to find the cheapest donut using reduceRight function Cheapest donut price = 1.5 Most expensive donut price = 2.5

Step 6: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 7: How to concatenate the elements from the sequence using reduceRight function Elements of donuts sequence concatenated = Plain Donut, Strawberry Donut, Glazed Donut

Step 7: How to concatenate the elements from the sequence using reduceRight function Elements of donuts sequence concatenated = Plain Donut, Strawberry Donut, Glazed Donut

Step 8: How to declare a value function to concatenate donut names Value function concatDonutNames = <function2>

Step 9: How to pass a function to reduceRight function Elements of donuts sequence concatenated by passing function to the reduceRight function = Plain Donut, Strawberry Donut, Glazed Donut 

 Step 10: How to use reduceRightOption to avoid exception if the collection is empty Using reduceRightOption will NOT throw any exception = None


Reverse:
def reverse: Repr 

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to get the elements of the sequence in reverse using the reverse method")
println(s"Elements of donuts in reversed order = ${donuts.reverse}")


println("\nStep 3: How to access each reversed element using reverse and foreach methods")
donuts.reverse.foreach(donut => println(s"donut = $donut")) 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to get the elements of the sequence in reverse using the reverse method Elements of donuts in reversed order = List(Glazed Donut, Strawberry Donut, Plain Donut)

Step 3: How to access each reversed element using reverse and foreach methods donut = Glazed Donut donut = Strawberry Donut donut = Plain Donut


reverseIterator
def reverseIterator: Iterator[A] 

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to print all elements in reversed order using reverseIterator function")
println(s"Elements of donuts in reversed order = ${donuts.reverseIterator.toList}")

println("\nStep 3: How to iterate through elements using foreach method")
val reverseIterator: Iterator[String] = donuts.reverseIterator
reverseIterator.foreach(donut => println(s"donut = $donut"))

output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to print all elements in reversed order using reverseIterator function Elements of donuts in reversed order = List(Glazed Donut, Strawberry Donut, Plain Donut)

Step 3: How to iterate through elements using foreach method donut = Glazed Donut donut = Strawberry Donut donut = Plain Donut

Scan:
def scan[B >: A, That](z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[Repr, B, That]): That 

Scan method iterations
0 + 1             =  1
1 + 2             =  3
1 + 2 + 3         =  6
1 + 2 + 3 + 4     = 10
1 + 2 + 3 + 4 + 5 = 15

println("Step 1: How to initialize a sequence of numbers")
val numbers: Seq[Int] = Seq(1, 2, 3, 4, 5)
println(s"Elements of numbers = $numbers")

println("\nStep 2: How to create a running total using the scan function")
val runningTotal: Seq[Int] = numbers.scan(0)(_ + _)
println(s"Running total of all elements in the collection = $runningTotal")

println("\nStep 3: How to create a running total using the scan function explicitly")
val runningTotal2: Seq[Int] = numbers.scan(0)((a, b) => a + b)
println(s"Running total of all elements in the collection = $runningTotal2")

output
Step 1: How to initialize a sequence of numbers Elements of numbers = List(1, 2, 3, 4, 5)

Step 2: How to create a running total using the scan function Running total of all elements in the collection = List(0, 1, 3, 6, 10, 15)

Step 3: How to create a running total using the scan function explicitly Running total of all elements in the collection = List(0, 1, 3, 6, 10, 15)

Scala Left:
def scanLeft[B, That](z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[Repr, B, That]): That
0 + 1             =    1 1 + 2             =    3 1 + 2 + 3         =    6 1 + 2 + 3 + 4     =   10 1 + 2 + 3 + 4 + 5 =   15 

println("Step 1: How to initialize a sequence of numbers")
val numbers: Seq[Int] = Seq(1, 3, 3, 4, 5)
println(s"Elements of numbers = $numbers")

println("\nStep 2: How to create a running total using the scanLeft function")
val runningTotal: Seq[Int] = numbers.scanLeft(0)(_ + _)
println(s"Running total of all elements in the collection = $runningTotal")

println("\nStep 3: How to create a running total using the scanLeft function explicitly")
val runningTotal2: Seq[Int] = numbers.scanLeft(0)((a, b) => a + b)
println(s"Running total of all elements in the collection = $runningTotal2")

output
Step 1: How to initialize a sequence of numbers Elements of numbers = List(1, 3, 3, 4, 5)

Step 2: How to create a running total using the scanLeft function Running total of all elements in the collection = List(0, 1, 4, 7, 11, 16)

Step 3: How to create a running total using the scanLeft function explicitly Running total of all elements in the collection = List(0, 1, 4, 7, 11, 16)

scanRight:
def scanRight[B, That](z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[Repr, B, That]): That
5 + 4 + 3 + 2 + 1 = 15 5 + 4 + 3 + 2     = 14 5 + 4 + 3         = 12 5 + 4             =  9 5 + 0             =  5 0 =  0

println("Step 1: How to initialize a sequence of numbers")
val numbers: Seq[Int] = Seq(1, 2, 3, 4, 5)
println(s"Elements of numbers = $numbers")

println("\nStep 2: How to create a running total using the scanRight function")
val runningTotal: Seq[Int] = numbers.scanRight(0)(_ + _)
println(s"Running total of all elements in the collection = $runningTotal")

println("\nStep 3: How to create a running total using the scanRight function explicitly")
val runningTotal2: Seq[Int] = numbers.scanRight(0)((a, b) => a + b)
println(s"Running total of all elements in the collection = $runningTotal2")

output
Step 1: How to initialize a sequence of numbers Elements of numbers = List(1, 2, 3, 4, 5)

Step 2: How to create a running total using the scanRight function Running total of all elements in the collection = List(15, 14, 12, 9, 5, 0)

Step 3: How to create a running total using the scanRight function explicitly Running total of all elements in the collection = List(15, 14, 12, 9, 5, 0)

Size:
def size: Int 

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to count the number of elements in the sequence using size function")
println(s"Size of donuts sequence = ${donuts.size}")

println("\nStep 3: How to use the count function")
println(s"Number of times element Plain Donut appear in donuts sequence = ${donuts.count(_ == "Plain Donut")}") 

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to count the number of elements in the sequence using size function Size of donuts sequence = 3

Step 3: How to use the count function Number of times element Plain Donut appear in donuts sequence = 1

Slice:
def slice(from: Int, until: Int): Repr

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to take a section from the sequence using the slice function")
println(s"Take elements from the sequence from index 0 to 1 = ${donuts.slice(0,1)}")
println(s"Take elements from the sequence from index 0 to 2 = ${donuts.slice(0,2)}")
println(s"Take elements from the sequence from index 0 to 3 = ${donuts.slice(1,3)}")


println("\nStep 3: Slice function where the index is out of range")
println(s"Take elements from the sequence from index 0 to 4 = ${donuts.slice(0,4)}")

Output
Step 1: How to initialize a Sequence of donuts Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

Step 2: How to take a section from the sequence using the slice function Take elements from the sequence from index 0 to 1 = List(Plain Donut) Take elements from the sequence from index 0 to 2 = List(Plain Donut, Strawberry Donut) Take elements from the sequence from index 0 to 3 = List(Strawberry Donut, Glazed Donut)

Step 3: Slice function where the index is out of range Take elements from the sequence from index 0 to 4 = List(Plain Donut, Strawberry Donut, Glazed Donut)

SortBy:
def sortBy[B](f: (A) ⇒ B)(implicit ord: math.Ordering[B]): Repr

// Start writing your ScalaFiddle code here
println("\nStep 1: How to create a case class to represent Donut objects")
case class Donut(name: String, price: Double)

println("\nStep 2: How to create a Sequence of type Donut")
val donuts: Seq[Donut] = Seq(Donut("Plain Donut", 1.5), Donut("Strawberry Donut", 2.0), Donut("Glazed Donut", 2.5))

println(s"Elements of donuts = $donuts")
println("\nStep 3: How to sort a sequence of case class objects using the sortBy function")
println(s"Sort a sequence of case class objects of type Donut, sorted by price = ${donuts.sortBy(donut => donut.price)}")

Output
Step 1: How to create a case class to represent Donut objects
Step 2: How to create a Sequence of type Donut
Elements of donuts = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))
Step 3: How to sort a sequence of case class objects using the sortBy function
Sort a sequence of case class objects of type Donut, sorted by price = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))


Sorted:
def sorted[B >: A](implicit ord: math.Ordering[B]): Repr

println("Step 1: How to initialize donut prices")
val prices: Seq[Double] = Seq(1.50, 2.0, 2.50)
println(s"Elements of prices = $prices")
println("\nStep 2: How to sort a sequence of type Double using the sorted function")
println(s"Sort a sequence of type Double by their natural ordering = ${prices.sorted}")

println("\nStep 3: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")
println("\nStep 4: How to sort a sequence of type String using the sorted function")
println(s"Sort a sequence of type String by their natural ordering = ${donuts.sorted}")

Output
Step 1: How to initialize donut prices
Elements of prices = List(1.5, 2, 2.5)
Step 2: How to sort a sequence of type Double using the sorted function
Sort a sequence of type Double by their natural ordering = List(1.5, 2, 2.5)
Step 3: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 4: How to sort a sequence of type String using the sorted function
Sort a sequence of type String by their natural ordering = List(Glazed Donut, Plain Donut, Strawberry Donut)

sortwith
def sortWith(lt: (A, A) ⇒ Boolean): Repr

println("\nStep 1: How to create a case class to represent Donut objects")
case class Donut(name: String, price: Double)
println("\nStep 2: How to create a Sequence of type Donut")
val donuts: Seq[Donut] = Seq(Donut("Plain Donut", 1.5), Donut("Strawberry Donut", 2.0), Donut("Glazed Donut", 2.5))
println(s"Elements of donuts = $donuts")

println("\nStep 3: How to sort a sequence of case class objects using the sortWith function")
println(s"Sort a sequence of case classes of type Donut, sorted with price = ${donuts.sortWith(_.price < _.price)}")

println("\nStep 4: How to sort a sequence of case class objects in ascending order using the sortWith function")
println(s"Sort a sequence of case classes of type Donut, sorted with price in ascending order = ${donuts.sortWith(_.price < _.price)}")
println(s"Sort a sequence of case classes of type Donut, sorted with price in ascending order explicitly = ${donuts.sortWith((d1,d2) => d1.price < d2.price)}")

Output
Step 1: How to create a case class to represent Donut objects
Step 2: How to create a Sequence of type Donut
Elements of donuts = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))
Step 3: How to sort a sequence of case class objects using the sortWith function
Sort a sequence of case classes of type Donut, sorted with price = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))
Step 4: How to sort a sequence of case class objects in ascending order using the sortWith function
Sort a sequence of case classes of type Donut, sorted with price in ascending order = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))
Sort a sequence of case classes of type Donut, sorted with price in ascending order explicitly = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2), Donut(Glazed Donut,2.5))

tail:
def tail: Repr
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to return all elements in the sequence except the head using the tail function")
println(s"Elements of donuts excluding the head = ${donuts.tail}")
println("\nStep 3: How to access the last element of the donut sequence by using the last function")
println(s"Last element of donut sequence = ${donuts.last}")

println("\nStep 4: How to access the first element of the donut sequence by using the head function")
println(s"First element of donut sequence = ${donuts.head}")

output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to return all elements in the sequence except the head using the tail function
Elements of donuts excluding the head = List(Strawberry Donut, Glazed Donut)
Step 3: How to access the last element of the donut sequence by using the last function
Last element of donut sequence = Glazed Donut
Step 4: How to access the first element of the donut sequence by using the head function
First element of donut sequence = Plain Donut

Take function:
def take(n: Int): Repr

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")
println("\nStep 2: How to take elements from the sequence using the take function")
println(s"Take the first donut element in the sequence = ${donuts.take(1)}")
println(s"Take the first and second donut elements in the sequence = ${donuts.take(2)}")
println(s"Take the first, second and third donut elements in the sequence = ${donuts.take(3)}")                                                                          

output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to take elements from the sequence using the take function
Take the first donut element in the sequence = List(Plain Donut)
Take the first and second donut elements in the sequence = List(Plain Donut, Strawberry Donut)
Take the first, second and third donut elements in the sequence = List(Plain Donut, Strawberry Donut, Glazed Donut)


TakeRight:
def takeRight(n: Int): Repr

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to take the last N elements using the takeRight function")
println(s"Take the last donut element in the sequence = ${donuts.takeRight(1)}")
println(s"Take the last two donut elements in the sequence = ${donuts.takeRight(2)}")
println(s"Take the last three donut elements in the sequence = ${donuts.takeRight(3)}")

output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to take the last N elements using the takeRight function
Take the last donut element in the sequence = List(Glazed Donut)
Take the last two donut elements in the sequence = List(Strawberry Donut, Glazed Donut)
Take the last three donut elements in the sequence = List(Plain Donut, Strawberry Donut, Glazed Donut)

TakeWhile
def takeWhile(p: (A) ⇒ Boolean): Repr
println("Step 1: How to initialize a List of donuts")

val donuts: Seq[String] = List("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts") 
 
println("\nStep 2: How to take elements from the List using the takeWhile function")
println(s"Take donut elements which start with letter P = ${donuts.takeWhile(_.charAt(0) == 'P')}")
println("\nStep 3: How to declare a predicate function to be passed-through to the takeWhile function")

val takeDonutPredicate: (String) => Boolean = (donutName) => donutName.charAt(0) == 'P'
println(s"Value function takeDonutPredicate = $takeDonutPredicate")

println("\nStep 4: How to take elements using the predicate function from Step 3")
println(s"Take elements using function from Step 3 = ${donuts.takeWhile(takeDonutPredicate)}")

output
Step 1: How to initialize a List of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to take elements from the List using the takeWhile function
Take donut elements which start with letter P = List(Plain Donut)
Step 3: How to declare a predicate function to be passed-through to the takeWhile function
Value function takeDonutPredicate = <function1>
Step 4: How to take elements using the predicate function from Step 3
Take elements using function from Step 3 = List(Plain Donut)
                                                                    
transpose:
def transpose[B](implicit asTraversable: (A) ⇒ GenTraversableOnce[B]): CC[CC[B]]

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to initialize donut prices")
val prices: Seq[Double] = Seq(1.50, 2.0, 2.50)
println(s"Elements of prices = $prices")

println("\nStep 3: How to create a List of donuts and prices")
val donutList = List(donuts, prices)
println(s"Sequence of donuts and prices = $donutList")

println("\nStep 4: How to pair each element from both donuts and prices Sequences using the transpose function")
println(s"Transposed list of donuts paired with their individual prices = ${donutList.transpose}")

Output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to initialize donut prices
Elements of prices = List(1.5, 2, 2.5)
Step 3: How to create a List of donuts and prices
Sequence of donuts and prices = List(List(Plain Donut, Strawberry Donut, Glazed Donut), List(1.5, 2, 2.5))
Step 4: How to pair each element from both donuts and prices Sequences using the transpose function
Transposed list of donuts paired with their individual prices = List(List(Plain Donut, 1.5), List(Strawberry Donut, 2), List(Glazed Donut, 2.5))

Union
def union(that: GenSet[A]): This
println("Step 1: How to initialize a Set of donuts")
val donuts1: Set[String] = Set("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts1 = $donuts1")
println("\nStep 2: How to initialize another Set of donuts")
val donuts2: Set[String] = Set("Plain Donut", "Chocolate Donut", "Vanilla Donut")
println(s"Elements of donuts2 = $donuts2")

println("\nStep 3: How to merge two Sets using union function")
println(s"Union of Sets donuts1 and donuts2 = ${donuts1 union donuts2}")
println(s"Union of Sets donuts2 and donuts1 = ${donuts2 union donuts1}")

println("\nStep 4: How to merge two Sets using ++ function")
println(s"Union of Sets donuts1 and donuts2 = ${donuts1 ++ donuts2}")
println(s"Union of Sets donuts2 and donuts1 = ${donuts2 ++ donuts1}")

output
Step 1: How to initialize a Set of donuts
Elements of donuts1 = Set(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to initialize another Set of donuts
Elements of donuts2 = Set(Plain Donut, Chocolate Donut, Vanilla Donut)
Step 3: How to merge two Sets using union function
Union of Sets donuts1 and donuts2 = Set(Vanilla Donut, Plain Donut, Chocolate Donut, Strawberry Donut, Glazed Donut)
Union of Sets donuts2 and donuts1 = Set(Vanilla Donut, Plain Donut, Chocolate Donut, Strawberry Donut, Glazed Donut)
Step 4: How to merge two Sets using ++ function
Union of Sets donuts1 and donuts2 = Set(Vanilla Donut, Plain Donut, Chocolate Donut, Strawberry Donut, Glazed Donut)
Union of Sets donuts2 and donuts1 = Set(Vanilla Donut, Plain Donut, Chocolate Donut, Strawberry Donut, Glazed Donut)


Unzip:
def unzip[A1, A2](implicit asPair: (A) ⇒ (A1, A2)): (CC[A1], CC[A2])

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to initialize a Sequence of donut prices")
val donutPrices = Seq[Double](1.5, 2.0, 2.5)
println(s"Elements of donut prices = $donutPrices")
println("\nStep 3: How to zip the donuts Sequence with their corresponding prices")
val zippedDonutsAndPrices: Seq[(String, Double)] = donuts zip donutPrices
println(s"Zipped donuts and prices = $zippedDonutsAndPrices")

println("\nStep 4: How to unzip the zipped donut sequence into separate donuts names and prices Sequences")
val unzipped: (Seq[String], Seq[Double]) = zippedDonutsAndPrices.unzip
println(s"Donut names unzipped = ${unzipped._1}")
println(s"Donut prices unzipped = ${unzipped._2}")

Output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to initialize a Sequence of donut prices
Elements of donut prices = List(1.5, 2, 2.5)
Step 3: How to zip the donuts Sequence with their corresponding prices
Zipped donuts and prices = List((Plain Donut,1.5), (Strawberry Donut,2), (Glazed Donut,2.5))
Step 4: How to unzip the zipped donut sequence into separate donuts names and prices Sequences
Donut names unzipped = List(Plain Donut, Strawberry Donut, Glazed Donut)
Donut prices unzipped = List(1.5, 2, 2.5)

Unzip3:
def unzip3[A1, A2, A3](implicit asTriple: (A) ⇒ (A1, A2, A3)): (CC[A1], CC[A2], CC[A3])

println("Step 1: How to initialize a Sequence of Tuple33 elements")
val donuts: Seq[(String, Double, String)] = Seq(("Plain Donut",1.5,"Tasty"), ("Glazed Donut",2.0,"Very Tasty"), ("Strawberry Donut",2.5,"Very Tasty"))
println(s"Donuts tuple3 elements = $donuts")

println("\nStep 2: How to call unzip3 function to unzip Tuple3 elements")
val unzipped: (Seq[String], Seq[Double], Seq[String]) = donuts.unzip3
println(s"Unzipped donut names = ${unzipped._1}")
println(s"Unzipped donut prices = ${unzipped._2}")
println(s"Unzipped donut taste = ${unzipped._3}")

output
Step 1: How to initialize a Sequence of Tuple3 elements
Donuts tuple3 elements = List((Plain Donut,1.5,Tasty), (Glazed Donut,2,Very Tasty), (Strawberry Donut,2.5,Very Tasty))
Step 2: How to call unzip3 function to unzip Tuple3 elements
Unzipped donut names = List(Plain Donut, Glazed Donut, Strawberry Donut)
Unzipped donut prices = List(1.5, 2, 2.5)
Unzipped donut taste = List(Tasty, Very Tasty, Very Tasty)

View:
def view: TraversableView[A, Repr]

println("Step 1: How to create a large numeric range and take the first 10 odd numbers")
val largeOddNumberList: List[Int] = (1 to 1000000).filter(_ % 2 != 0).take(10).toList
println(s"\nStep 2: How to lazily create a large numeric range and take the first 10 odd numbers")
val lazyLargeOddNumberList = (1 to 1000000).view.filter(_ % 2 != 0).take(10).toList
println(s"Lazily take the first 100 odd numbers from lazyLargeOddNumberList = ${lazyLargeOddNumberList}")

output
Step 1: How to create a large numeric range and take the first 10 odd numbers
Step 2: How to lazily create a large numeric range and take the first 10 odd numbers
Lazily take the first 100 odd numbers from lazyLargeOddNumberList = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)

WithFilter:
def withFilter(p: (A) ⇒ Boolean): FilterMonadic[A, Repr]

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = List("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")
println("\nStep 2: How to filter elements using the withFilter function")
 donuts
 .withFilter(_.charAt(0) == 'P')
 .foreach(donut => println(s"Donut starting with letter P = $donut"))

output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to filter elements using the withFilter function
Donut starting with letter P = Plain Donut

ZIP:
def zip[B](that: GenIterable[B]): Iterable[(A, B)]

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")
println("\nStep 2: How to initialize a Sequence of donut prices")
val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donut prices = $donutPrices")

println("\nStep 3: How to use zip method to zip two collections")
val zippedDonutsAndPrices: Seq[(String, Double)] = donuts zip donutPrices
println(s"Zipped donuts and prices = $zippedDonutsAndPrices")
println("\nStep 4: How to use unzip method to un-merge a zipped collections")
val unzipped: (Seq[String], Seq[Double]) = zippedDonutsAndPrices.unzip
println(s"Donut names unzipped = ${unzipped._1}")
println(s"Donut prices unzipped = ${unzipped._2}")

output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to initialize a Sequence of donut prices
Elements of donut prices = List(1.5, 2, 2.5)
Step 3: How to use zip method to zip two collections
Zipped donuts and prices = List((Plain Donut,1.5), (Strawberry Donut,2), (Glazed Donut,2.5))
Step 4: How to use unzip method to un-merge a zipped collections
Donut names unzipped = List(Plain Donut, Strawberry Donut, Glazed Donut)
Donut prices unzipped = List(1.5, 2, 2.5)

zipwithIndex
def zipWithIndex: Iterable[(A, Int)]

println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

println("\nStep 2: How to zip the donuts Sequence with their corresponding index using zipWithIndex method")
val zippedDonutsWithIndex: Seq[(String, Int)] = donuts.zipWithIndex
zippedDonutsWithIndex.foreach{ donutWithIndex =>
 println(s"Donut element = ${donutWithIndex._1} is at index = ${donutWithIndex._2}")
}

Output
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
Step 2: How to zip the donuts Sequence with their corresponding index using zipWithIndex method
Donut element = Plain Donut is at index = 0
Donut element = Strawberry Donut is at index = 1
Donut element = Glazed Donut is at index = 2


                                                  


                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       










Python Challenges Program

Challenges program: program 1: #Input :ABAABBCA #Output: A4B3C1 str1="ABAABBCA" str2="" d={} for x in str1: d[x]=d...