List in Scala Programming Language

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

List:

All the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat.

Run the following commands:

·        By default immutable

·        They do not maintain order

·        List can’t be accessed by their Index.

1. Example program to show usage of the basic List operational methods:

package Collection
object List1 {

defmain(args: Array[String]) {
val lang1 = "Python" :: ("Machine Learning" ::( "Sql":: Nil))
val num = Nil

println( "Best of Programming Language : " + lang1.head )

println( "Other Programming Language : " + lang1.tail )

println( "Check if Set is empty : " + lang1.isEmpty )

println( "Check if num is empty : " + num.isEmpty)
  }
}

2. Example program to show usage of the List with respect to concatenation:

package Collection
object List2 {

defmain(args: Array[String]) {

val lang1 = "Python" :: ("DataScience"::("Sql":: Nil))

val lang2 = "Hadoop" :: ("Scala" :: ("AWS":: Nil))

// using two Lists with ::: as operator

var lang = lang1 ::: lang2

println( "lang1 ::: lang2 : " + lang )

// using two Lists with Set .:::() method

lang = lang1.:::(lang2)

println( "lang1.:::(lang2) : " + lang )

// passing two lists as arguments

lang = List.concat(lang1, lang2)

println( "List.concat(lang1, lang2) : " + lang  )

  }
}

3. Program to create a list with zero or more copies of the same element using List.fill() method.

package Collection
object List3 {
defmain(args: Array[String]) {

// Repeatedly prints PrwaTech four times.

val center = List.fill(4)("PrwaTech")
println( "Learning Center : " + center )

// Repeatedly prints 6, 12 times.

val num = List.fill(12)(6)
println( "num : " + num  )
  }
}

4. Program to Sort and reverse all elements of the list.

package Collection
object List4 {

defmain(args: Array[String]) {

val lang1 = "Python" :: ("Hadoop" :: ("DataScience" :: ("Sql" :: ("AWS" :: ("Scala" :: Nil)))))

val lang2 = lang1.sorted

println("List Before Sorting : " + lang1)

println("List After Sorting : " + lang2)

println("Before reversing Lang List : " + lang2)

println("After reversing Lang List : " + lang2.reverse)
  }
}

Quick Support

image image