Scala Lists are always immutable and dynamically growable (but arrays are fixed in Scala once you create with some size ). If you want Mutable List then prefer to use ListBuffer(it is in scala.collection.mutable package).
Here will see about creation of List and operations on it.
Different ways of Creating a List :
Val samplelist = List(1,2,3) // created list with name samplelist
Val samplelist1 = 7:: 8::10::Nil //created list with name samplelist1
Val samplelist2 = “a”:: (“b”:: ( “c” ::Nil)) //created list with name samplelist2
The above all creates the list and have same meaning.
Most common operator you’ll use with lists is ‘::’, using this operator we can prepend a new element to the beginning of an existing list, and returns the resulting list. List has a method named ‘:::’ for list concatenation
Let’s create some lists and perform some operations.
scala> val a = List(1,2,3) // created list with name a
a: List[Int] = List(1, 2, 3)
scala> val b = List(“x” , “y”, “z”) // created list with name b
b: List[String] = List(x, y, z)
scala> val c = a::: b// we did concatenation of List a and List b, and stored result in List c
c: List[Any] = List(1, 2, 3, x, y, z)
scala> val d = c ::: 100 :: Nil // we added 100 to the List c and stored in List d
d: List[Any] = List(1, 2, 3, x, y, z, 100)
Accesing List elements:
scala> d(3) //here we are accessing 4th element(index is 3) in List d
res4: Any = x
scala> d(5) //6th element in List d
res5: Any = z
List methods:
All operations on lists can be expressed in terms of the following three:
Head returns the first element of a list
Tail returns a list consisting of all elements except the first
isEmpty returns true if the list is empty
scala> d.head //returns first element in List d
res14: Any = 1
scala> d.tail //returns the all elements in the List d except first element(which is head)
res15: List[Any] = List(2, 3, x, y, z, 100)
scala> d.isEmpty //checking wheather list is empty or not
res16: Boolean = false
The head and tail methods are defined only for non-empty lists. When selected from an empty list, they throw an exception.
length of list:
scala> d.length //finnding length of List d
res19: Int = 7
Accessing the end of a list: init and lastlast returns the last element of a (nonempty) list, whereas init returns a list consisting of all elements except the last one. These methods throw an exception when applied to an empty list
scala> val mylist = List(1,2,3,”a”,”b”,”c”,”d”) // created list with name mylist
mylist: List[Any] = List(1, 2, 3, a, b, c, d)
scala> mylist.init //returns all elements except last element in mylist
res20: List[Any] = List(1, 2, 3, a, b, c)
scala> mylist.last //returns only last element
res21: Any = d
Reverse a List:
scala> val mylist1 = List(1,2,3,4,5,6,7,8,9,10) //create list with name mylist1
mylist1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> mylist1.reverse //performing reverse operation on list mylist1
res25: List[Int] = List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
drop, take, and splitAt methods :
drop(n) – it will return the values in the List from the index n we passed to the last of List
take(n) – it will return first n values from the list(where n we need to provide)
splitAt(n) – it will split the list in to two lists. it will split like from n index to last one list and before n index one list
// created list with name mylist2
scala> val mylist2 = List(“hi”, “hello”,”howru”,”goodbye”,”thankyou”,”welcome”)
mylist2: List[String] = List(hi, hello, howru, goodbye, thankyou, welcome)
scala> mylist2.drop(3)
res1: List[String] = List(goodbye, thankyou, welcome)
scala> mylist2.take(4)
res2: List[String] = List(hi, hello, howru, goodbye)
scala> mylist2.splitAt(2)
res4: (List[String], List[String]) = (List(hi, hello),List(howru, goodbye, thankyou, welcome))
Flattening a list of lists: flatten
The flatten method takes a list of lists and flattens it out to a single list
scala>List(List(1, 2), List(3), List(), List(4, 5)).flatten //here we are flattening 4 lists
res14: List[Int] = List(1, 2, 3, 4, 5)
Zipping lists: zip and unzip
The zip operation takes two lists and forms a list of pairs:
scala> val zlist1 = List(11,22,33,44,55)
zlist1: List[Int] = List(11, 22, 33, 44, 55)
scala> val zlist2 = List(“aa”,”bb”,”cc”,”dd”,”ee”)
zlist2: List[String] = List(aa, bb, cc, dd, ee)
scala> zlist1.zip(zlist2)
res5: List[(Int, String)] = List((11,aa), (22,bb), (33,cc), (44,dd), (55,ee))
zipWithIndex:
it will zip each element with its index and return the list of pairs
scala> zlist2.zipWithIndex
res6: List[(String, Int)] = List((aa,0), (bb,1), (cc,2), (dd,3), (ee,4))
unzip: It unzips the pairs and returns two lists
scala> val zlist3 = zlist1.zip(zlist2)
zlist3: List[(Int, String)] = List((11,aa), (22,bb), (33,cc), (44,dd), (55,ee))
scala> zlist3.unzip //unzipping zlist3 here
res7: (List[Int], List[String]) = (List(11, 22, 33, 44, 55),List(aa, bb, cc, dd, ee))
mkstring:
scala> val list11 = List(“how”,”r”,”u”,”good”,”bye”) //created list with name list11
list11: List[String] = List(how, r, u, good, bye)
scala> list11 mkString “” //when we apply mkstring with some delimiter
res10: String = howrugoodbye
Converting lists: iterator, toArray, copyToArray
scala> val list11 = List(“how”,”r”,”u”,”good”,”bye”)
list11: List[String] = List(how, r, u, good, bye)
List to Array Conversion:
scala> val arrlist = list11.toArray
arrlist: Array[String] = Array(how, r, u, good, bye)
Iterator:
scala> val itr = list11.iterator
itr: Iterator[String] = non-empty iterator
scala>itr.next
res16: String = how
scala>itr.next
res17: String = r
A fold left operation “(z /: xs) (op)” involves three objects: a start value z, a list xs, and a binary operation op. The result of the fold is op applied between successive elements of the list prefixed by z.
For instance: (z /: List(a, b, c)) (op) equals op(op(op(z, a), b), c)
scala> val mylist = List(1,2,3,4,5)
mylist: List[Int] = List(1, 2, 3, 4, 5)
scala> (0/:mylist)(_+_)
res23: Int = 15
Reversing a List Using FoldLeft.
scala> (List[Int]()/:mylist){(_1,_2)=>_2 :: _1}
res32: List[Int] = List(5, 4, 3, 2, 1)
The operator has as an analog that produces right-leaning trees. For instance:
(List(a, b, c) z) (op) equals op(a, op(b, op(c, z)))
sortWith:
scala> List(1,2,3,4,5) sortWith(_>_)
res34: List[Int] = List(5, 4, 3, 2, 1)
scala> List(1,2,3,4,5) sortWith(_<_)
res35: List[Int] = List(1, 2, 3, 4, 5)
Exceptions while you apply operations on Empty List:
scala> val aa = List()
aa: List[Nothing] = List()
scala> aa.head
java.util.NoSuchElementException: head of empty list
scala> aa.init
java.lang.UnsupportedOperationException: empty.init
scala> aa.last
java.util.NoSuchElementException
Try ur self these below methods on lists
Mapping over lists: map, flatMap and foreach
Filtering lists: filter, partition, find, takeWhile, dropWhile, and span
References:
Programming in Scala Book, Martin Odersky