Scala Lists

by | Jul 20, 2018 | Apache Spark, Big Data, Scala-example | 0 comments

Create listsScala_logo

Examples that define the lists to be used in the rest of the sections of the post

val list1 = 1::2::3::4::5::Nil
val list2 = List(1,2,3,4,5)
val list3 = List.range(1,6)
val list4 = List.range(1,6,2)
val list5 = List.fill(5)(1)
val list6 = List("Peter","Tommy","Sonia","Mary")
val list7 = List.tabulate(5)(n => n * n)
list1: List[Int] = List(1, 2, 3, 4, 5)
list2: List[Int] = List(1, 2, 3, 4, 5)
list3: List[Int] = List(1, 2, 3, 4, 5)
list4: List[Int] = List(1, 3, 5)
list5: List[Int] = List(1, 1, 1, 1, 1)
list6: List[String] = List(Peter, Tommy, Sonia, Mary)
list7: List[Int] = List(0, 1, 4, 9, 16)

 

Transform dataframe column into list

val df = Seq(
    ("one", 2.0),
    ("two", 1.5),
    ("three", 8.0)
  ).toDF("id", "value")
  
val list = df.select("id").map(r => r.getString(0)).collect.toList 
lista
res: List[String] = List(one, two, three)

List operations

Foreach – add Items

var sum = 0
 list1.foreach(sum += _)
sum: Int = 15

For – displaying items

for (name <- list6) println(name)
Peter
Tommy
Sonia
Mary

For – displaying items with restrictions

for (name <- list6 if name.startsWith("T")){
  println(name)
}
Tommy

 

Adding items to a list

val list_total = "Julia" :: list6
list_total: List[String] = List(Julia, Peter, Tommy, Sonia, Mary)

 

Join lists

val list_total1 = List.concat(list1, list2)
val list_total2 = list1 ++ list2
val list_total3 = list1 ::: list2
list_total1: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) 
list_total2: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) 
list_total3: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

 

Flatten lists

List(List(1), List(2), List(3)).flatten
res: List[Int] = List(1, 2, 3)

 

Filters on lists

Simple filters

list1.filter( _ > 2 )
list1.filter( _ % 2 == 0)
res1: List[Int] = List(3, 4, 5)
res2: List[Int] = List(2, 4)

Class Filters

case class Person(name: String, surname: String, age: Integer, salary: Integer)

val person1 = Person("Peter","Garcia",24,24000)
val person2 = Person("Juan","Garcia",26,27000)
val person3 = Person("Lola","Martin",29,31000)
val person4 = Person("Sara","Garcia",35,34000)

val people= List(person1,person2,person3,person4)

people.filter(_.surname== "Garcia")
 .filter(_.age> 25)
 .map(_.name)
res: List[String] = List(Juan, Sara)

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *