0% found this document useful (0 votes)
16 views15 pages

Hyercar

Uploaded by

abijeet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views15 pages

Hyercar

Uploaded by

abijeet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

List (Day 1 of 2)

1. Creating a List in Scala


a. List of String
scala> val colors: List[String] = List("Red", "Green",
"Yellow")
colors: List[String] = List(Red, Green, Yellow)

b. No need to specify data type. Scala can interpret it.


scala> val colors = List("Red", "Green", "Yellow")
colors: List[String] = List(Red, Green, Yellow)

c. List of Integers
scala> val evenNumbers = List (2,4,6,8)
evenNumbers: List[Int] = List(2, 4, 6, 8)

d. List of Integers and Double will be considered as List of Double


scala> val numbers = List (2.0,4,6.5,8)
numbers: List[Double] = List(2.0, 4.0, 6.5, 8.0)

e. List of Integers, Double and String will be considered as List of Any


scala> val list = List (2,5.2,"Hello")
list: List[Any] = List(2, 5.2, Hello)

f. 2 Dimensional List
scala> val matrix = List(
| List(1,2,3),
| List(4,5,6),
| List(7,8,9)
| )
matrix: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6),
List(7, 8, 9))

Note: List[Int] and List[Double] makes List[AnyVal]


scala> val matrix = List(
| List(1,2,3),
| List(4.1,5,6),
| List(7,8,9)
| )
matrix: List[List[AnyVal]] = List(List(1, 2, 3), List(4.1,
5.0, 6.0), List(7, 8, 9))
2. List is immutable {Array is mutable}
scala> val evenNumbers = List (2,4,6,8)
evenNumbers: List[Int] = List(2, 4, 6, 8)

scala> evenNumbers(0)
res0: Int = 2

scala> evenNumbers(1)
res1: Int = 4

scala> evenNumbers(2)
res2: Int = 6

scala> evenNumbers(3)
res3: Int = 8

scala> evenNumbers(1) = 7 //BCOZ LIST IS IMMUTABLE


<console>:9: error: value update is not a member of List[Int]
evenNumbers(1) = 7
^

scala> val evenNumbers = Array (2,4,6,8)


evenNumbers: Array[Int] = Array(2, 4, 6, 8)

scala> evenNumbers(0)
res5: Int = 2

scala> evenNumbers(1)
res6: Int = 4

scala> evenNumbers(2)
res7: Int = 6

scala> evenNumbers(3)
res8: Int = 8

scala> evenNumbers(1) = 7 // BCOZ ARRAY IS MUTABLE


scala> evenNumbers
res10: Array[Int] = Array(2, 7, 6, 8)
3. Define List using :: and Nil
scala> val colors = List("Red", "Green", "Yellow")
colors: List[String] = List(Red, Green, Yellow)

scala> val colors = "Red" :: ("Green" :: ("Yellow" :: Nil))


colors: List[String] = List(Red, Green, Yellow)

scala> val evenNumbers = 2 :: (4 :: (6 :: (8 :: Nil)))


evenNumbers: List[Int] = List(2, 4, 6, 8)

scala> val matrix = (1::(2::(3::Nil))) :: (4::(5::(6::Nil))) ::


(7::(8::(9::Nil))) :: Nil
matrix: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6),
List(7, 8, 9))

scala> val matrix = ((1::(2::(3::Nil))) :: (4::(5::(6::Nil))) ::


(7::(8::(9::Nil))) :: Nil)
matrix: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6),
List(7, 8, 9))

4. Different ways of defining a List

scala> val numbers = List.range(1,100)


numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99)

scala> val evenNumbers = List.range(2,100,2)


evenNumbers: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52,
54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84,
86, 88, 90, 92, 94, 96, 98)

scala> val oddNumbers = List.range(1,100,2)


oddNumbers: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51,
53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83,
85, 87, 89, 91, 93, 95, 97, 99)
scala> val oddNumbers = (1 to 100 by 2).toList
oddNumbers: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51,
53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83,
85, 87, 89, 91, 93, 95, 97, 99)

scala> val oddNumbers = (1 to 100 by 2) toList


warning: there were 1 feature warning(s); re-run with -feature
for details
oddNumbers: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51,
53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83,
85, 87, 89, 91, 93, 95, 97, 99)

scala> val oddNumbers = (1 to 100 by 2).toList


oddNumbers: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51,
53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83,
85, 87, 89, 91, 93, 95, 97, 99)

5. Simple Operations on List


a. Define a List of String
scala> val colors = List("Red", "Green", "Yellow")
colors: List[String] = List(Red, Green, Yellow)

b. head: 1st element of List


scala> colors.head
res11: String = Red

c. tail: Except 1st element of List, all other elements


scala> colors.tail
res12: List[String] = List(Green, Yellow)

d. Define a empty List


scala> val numbers = Nil
numbers: scala.collection.immutable.Nil.type = List()

e. isEmpty: If the List is a empty List


scala> numbers.isEmpty
res13: Boolean = true

scala> colors.isEmpty
res14: Boolean = false
f. size: Check the size of List
scala> colors.size
res15: Int = 3

scala> numbers.size
res16: Int = 0

g. mkString: Convert the List into String


scala> val availableColors = colors.mkString(",")
availableColors: String = Red,Green,Yellow

scala> val availableColors = colors.mkString("We are having


these colors: ", "," , " only. Please pick among these.")
availableColors: String = We are having these colors:
Red,Green,Yellow only. Please pick among these.

6. Adding Elements to a List and accessing it

a. Create a List of String


scala> val colors = List ("Red", "Green", "Yellow")
colors: List[String] = List(Red, Green, Yellow)

b. Add Blue at the end. It wont work because you defined as a val
scala> colors = colors:+"Blue"
<console>:8: error: reassignment to val
colors = colors:+"Blue"
^

c. Define the List as var so you can reassign


scala> var colors = List ("Red", "Green", "Yellow")
colors: List[String] = List(Red, Green, Yellow)

d. Create a new list with “Blue” and overwrite colors (ONLY POSSIBLE BECAUSE colors IS
DEFINED AS var )
scala> colors = colors:+"Blue"
colors: List[String] = List(Red, Green, Yellow, Blue)

e. Add elements to List at start


scala> colors = "Orange"+:colors
colors: List[String] = List(Orange, Red, Green, Yellow, Blue)

scala> colors = "Voilet"::colors


colors: List[String] = List(Voilet, Orange, Red, Green,
Yellow, Blue)
scala> colors = "Voilet"::colors
colors: List[String] = List(Voilet, Voilet, Orange, Red,
Green, Yellow, Blue)

scala> colors = "Voilet"::colors


colors: List[String] = List(Voilet, Voilet, Voilet, Orange,
Red, Green, Yellow, Blue)

f. Get unique elements from the List


scala> colors = colors.distinct
colors: List[String] = List(Voilet, Orange, Red, Green,
Yellow, Blue)

g. Access the elements in a List using a for loop


scala> for (color <- colors) {println(color)}
Voilet
Orange
Red
Green
Yellow
Blue

h. Access the elements in a List using a foreach


scala> colors.foreach(x => println(x))
Voilet
Orange
Red
Green
Yellow
Blue

scala> colors.foreach(println(_))
Voilet
Orange
Red
Green
Yellow
Blue

scala> colors.foreach(println)
Voilet
Orange
Red
Green
Yellow
Blue
scala> val numbers = List(2,4,6,8)
numbers: List[Int] = List(2, 4, 6, 8)

scala> numbers.foreach(x => println(x*2))


4
8
12
16

scala> numbers.foreach(x => println(x*2))


4
8
12
16

7. Some complex operations on List

a. Define a List of Stings (colors)


scala> val colors = List("Voilet", "Orange", "Red", "Green",
"Yellow", "Blue")
colors: List[String] = List(Voilet, Orange, Red, Green,
Yellow, Blue)

b. Access the element at index 2


scala> colors(2)
res32: String = Red

c. Modify the element in index 2 [YOU CAN NOT MODIFY THE CONTENTS OF LIST BECAUSE LIST
IS IMMUTABLE]
scala> colors(2) = "RED"
<console>:9: error: value update is not a member of
List[String]
colors(2) = "RED"
^

NOTE: EVEN IF THE LIST WAS DEFINED AS VAR, YOU STILL CAN NOT MODIFY THE CONTENTS OF
LIST BECAUSE LIST IS IMMUTABLE
scala> var colors = List("Voilet", "Orange", "Red", "Green",
"Yellow", "Blue")
colors: List[String] = List(Voilet, Orange, Red, Green,
Yellow, Blue)
scala> colors(2) = "RED"
<console>:9: error: value update is not a member of
List[String]
colors(2) = "RED"
^
d. Filter the elements
scala> var colorsWithLength3 = colors.filter(x=>x.length==3)
colorsWithLength3: List[String] = List(Red)

Short Hand Notation


scala> var colorsWithLength3 = colors.filter(_.length==3)
colorsWithLength3: List[String] = List(Red)

scala> var greenColor = colors.filter(x=>x=="Green")


greenColor: List[String] = List(Green)

scala> var colorsWithWordAsn =


colors.filter(x=>x.contains("n"))
colorsWithWordAsn: List[String] = List(Orange, Green)

scala> var colorsWithLength5orMore =


colors.filter(x=>x.length>=5)
colorsWithLength5orMore: List[String] = List(Voilet, Orange,
Green, Yellow)

scala> colorsWithLength5orMore.exists(x=>x=="Green")
res35: Boolean = true

scala> colorsWithLength5orMore.exists(x=>x=="Blue")
res36: Boolean = false

NOTE: IF THINGS ARE NOT CLEAR, JUST PUT A PRINT STATEMENT, SO YOU MAKE OUT THINGS
BETTER, EXAMPLE BELOW

scala> colorsWithLength5orMore.exists(color=>{println(color);
color=="Blue"})
Voilet
Orange
Green
Yellow
res41: Boolean = false
List (Day 2 of 2)

8. fill - Creating list with same data

scala> val colors = List.fill(5) ("Red")


colors: List[String] = List(Red, Red, Red, Red, Red)

scala> val numbers = List.fill(5) (2.5)


numbers: List[Double] = List(2.5, 2.5, 2.5, 2.5, 2.5)

9. tabulate – You can apply some function to generate elements in list

scala> val numbers = List.tabulate(5) (x => x + 10)


numbers: List[Int] = List(10, 11, 12, 13, 14)

scala> val squaredNumbers = List.tabulate(5) (x => x * x)


squaredNumbers: List[Int] = List(0, 1, 4, 9, 16)

val matrix = List.tabulate(3,3) ((r,c) => r * c)


matrix: List[List[Int]] = List(List(0, 0, 0), List(0, 1, 2),
List(0, 2, 4))

Explaination
rows\columns 0 1 2
0 0 0 0
1 0 1 2
2 0 2 4

scala> val matrix = List.tabulate(3,3) (_ * _)


matrix: List[List[Int]] = List(List(0, 0, 0), List(0, 1, 2),
List(0, 2, 4))

10. reverse – Reverse the order of list

scala> val numbers = List(0,1,2,5,9,1,25,18)


numbers: List[Int] = List(0, 1, 2, 5, 9, 1, 25, 18)

scala> numbers.reverse
res0: List[Int] = List(18, 25, 1, 9, 5, 2, 1, 0)
Note: Contents of list will be changed, List is immutable
scala> numbers
res1: List[Int] = List(0, 1, 2, 5, 9, 1, 25, 18)

Note: You can put it in a new list


scala> val newNumbers = numbers.reverse
newNumbers: List[Int] = List(18, 25, 1, 9, 5, 2, 1, 0)

scala> newNumbers
res2: List[Int] = List(18, 25, 1, 9, 5, 2, 1, 0)

11. Sorting the List


A. sorted – Sort in ascending or descending order

scala> val numbers = List(0,1,2,5,9,1,25,18)


numbers: List[Int] = List(0, 1, 2, 5, 9, 1, 25, 18)

Note: Sort in ascending order by default


scala> numbers.sorted
res4: List[Int] = List(0, 1, 1, 2, 5, 9, 18, 25)

Note: Sort in descending order using reverse


scala> numbers.sorted(Ordering.Int.reverse)
res5: List[Int] = List(25, 18, 9, 5, 2, 1, 1, 0)

B. sortBy

scala> val numbers = List(0,1,2,5,9,1,25,18)


numbers: List[Int] = List(0, 1, 2, 5, 9, 1, 25, 18)

scala> numbers.sortBy(x=>x)
res6: List[Int] = List(0, 1, 1, 2, 5, 9, 18, 25)

scala> numbers.sortBy(x=>x).reverse
res7: List[Int] = List(25, 18, 9, 5, 2, 1, 1, 0)

Note: In the below example we are sorting on basis of 2/x result


scala> numbers.sortBy(x=>2/x)
res12: List[Int] = List(5, 9, 25, 18, 2, 1, 1)

Complex

# Defining a case class


scala> case class cars(val name:String, val cost:Int)
defined class cars

# Creating object for case class


scala> val car1 = cars("Mercedes", 50000)
car1: cars = cars(Mercedes,50000)

scala> val car2 = cars("BMW", 80000)


car2: cars = cars(BMW,80000)

scala> val car3 = cars("Jaquar", 70000)


car3: cars = cars(Jaquar,70000)

# Making the list of all cars


scala> val listOfCars = List(car1,car2,car3)
listOfCars: List[cars] = List(cars(Mercedes,50000),
cars(BMW,80000), cars(Jaquar,70000))

# Sort in ascending order of cost


scala> listOfCars.sortBy(c => c.cost)
res13: List[cars] = List(cars(Mercedes,50000),
cars(Jaquar,70000), cars(BMW,80000))

scala> listOfCars.sortBy(_.cost)
res14: List[cars] = List(cars(Mercedes,50000),
cars(Jaquar,70000), cars(BMW,80000))

# Sort in descending order of cost


scala> listOfCars.sortBy(_.cost).reverse
res15: List[cars] = List(cars(BMW,80000), cars(Jaquar,70000),
cars(Mercedes,50000))

# Sort in ascending order of name


scala> listOfCars.sortBy(_.name)
res16: List[cars] = List(cars(BMW,80000), cars(Jaquar,70000),
cars(Mercedes,50000))

C. sortWith
scala> val numbers = List(0, 1, 2, 5, 9, 1, 25, 18)
numbers: List[Int] = List(0, 1, 2, 5, 9, 1, 25, 18)

scala> numbers.sortWith((x,y)=>x<y)
res18: List[Int] = List(0, 1, 1, 2, 5, 9, 18, 25)

scala> numbers.sortWith((x,y)=>x>y)
res19: List[Int] = List(25, 18, 9, 5, 2, 1, 1, 0)

scala> numbers.sortWith(_>_)
res20: List[Int] = List(25, 18, 9, 5, 2, 1, 1, 0)

Complex

# Defining a case class


scala> case class cars(val name:String, val cost:Int)
defined class cars

# Creating object for case class


scala> val car1 = cars("Mercedes", 50000)
car1: cars = cars(Mercedes,50000)

scala> val car2 = cars("BMW", 80000)


car2: cars = cars(BMW,80000)

scala> val car3 = cars("Jaquar", 70000)


car3: cars = cars(Jaquar,70000)

# Making the list of all cars


scala> val listOfCars = List(car1,car2,car3)
listOfCars: List[cars] = List(cars(Mercedes,50000),
cars(BMW,80000), cars(Jaquar,70000))

# Ascending order of cost


scala> listOfCars.sortWith((c1,c2) => c1.cost < c2.cost)
res21: List[cars] = List(cars(Mercedes,50000),
cars(Jaquar,70000), cars(BMW,80000))

# Descending order of cost


scala> listOfCars.sortWith((c1,c2) => c1.cost > c2.cost)
res22: List[cars] = List(cars(BMW,80000), cars(Jaquar,70000),
cars(Mercedes,50000))

# Descending order of cost using shorthand notation


scala> listOfCars.sortWith(_.cost > _.cost)
res23: List[cars] = List(cars(BMW,80000), cars(Jaquar,70000),
cars(Mercedes,50000))

# Descending order of name using shorthand notation


scala> listOfCars.sortWith(_.name > _.name)
res24: List[cars] = List(cars(Mercedes,50000),
cars(Jaquar,70000), cars(BMW,80000))

# More complex

scala> def sortingLogic(c1:cars,c2:cars) =


| {
| println(c1.cost + c1.name)
| println(c2.cost + c2.name)
| c1.cost > c2.cost
| }
sortingLogic: (c1: cars, c2: cars)Boolean

scala> listOfCars.sortWith(sortingLogic)
80000BMW
50000Mercedes
70000Jaquar
80000BMW
80000BMW
70000Jaquar
70000Jaquar
50000Mercedes
70000Jaquar
80000BMW
80000BMW
70000Jaquar
res25: List[cars] = List(cars(BMW,80000), cars(Jaquar,70000),
cars(Mercedes,50000))

12. Mutable ListBuffer

a. import
import scala.collection.mutable.ListBuffer

b. create a empty ListBuffer of Int


scala> val numbers = new ListBuffer[Int]()
numbers: scala.collection.mutable.ListBuffer[Int] =
ListBuffer()

c. Add elements to ListBuffer


scala> numbers+=0
res27: numbers.type = ListBuffer(0)

scala> numbers+=1
res28: numbers.type = ListBuffer(0, 1)

scala> numbers+=2
res29: numbers.type = ListBuffer(0, 1, 2)

scala> numbers+=(2,4,6,8,10)
res30: numbers.type = ListBuffer(0, 1, 2, 2, 4, 6, 8, 10)
d. Remove elements from ListBuffer
scala> numbers-=(2,10)
res31: numbers.type = ListBuffer(0, 1, 2, 4, 6, 8)

e. Convert ListBuffer to a List


scala> val numbersList = numbers.toList
numbersList: List[Int] = List(0, 1, 2, 4, 6, 8)

f. You can not add or remove elements in a List because List is immutable
scala> numbersList+=5
<console>:11: error: value += is not a member of List[Int]
numbersList+=5
^
g. Use Tab to see all the methods that you can apply to a ListBuffer
scala> numbers.
++ ++: ++=
++=: +: +=
+=: - --
--= -= /:
/:\ :+ :\
addString aggregate andThen
append appendAll apply
applyOrElse asInstanceOf canEqual
clear clone collect
collectFirst combinations companion
compose contains containsSlice
copyToArray copyToBuffer corresponds
count diff distinct
drop dropRight dropWhile
endsWith exists filter
filterNot find flatMap
flatten fold foldLeft
foldRight forall foreach
genericBuilder groupBy grouped
hasDefiniteSize head headOption
indexOf indexOfSlice indexWhere
indices init inits
insert insertAll intersect
isDefinedAt isEmpty isInstanceOf
isTraversableAgain iterator last
lastIndexOf lastIndexOfSlice lastIndexWhere
lastOption length lengthCompare
lift map mapResult
max maxBy min
minBy mkString nonEmpty
orElse padTo par
partition patch permutations
prefixLength prepend prependAll
prependToList product readOnly
reduce reduceLeft reduceLeftOption
reduceOption reduceRight reduceRightOption
remove repr result
reverse reverseIterator reverseMap
runWith sameElements scan
scanLeft scanRight segmentLength
seq size sizeHint
sizeHintBounded slice sliding
sortBy sortWith sorted
span splitAt startsWith
stringPrefix sum tail
tails take takeRight
takeWhile to toArray
toBuffer toIndexedSeq toIterable
toIterator toList toMap
toSeq toSet toStream
toString toTraversable toVector
transform transpose trimEnd
trimStart union unzip
unzip3 update updated
view withFilter zip
zipAll zipWithIndex

h. Apply map to ListBuffer


scala> numbers.
| map(x => x*x)
res33: scala.collection.mutable.ListBuffer[Int] =
ListBuffer(0, 1, 4, 16, 36, 64)

You might also like