Showing posts with label aaeae| ListBuffer. Show all posts
Showing posts with label aaeae| ListBuffer. Show all posts

Friday, December 2, 2016

Which Sequence to use?

Sequences
  1. List #373
    1. Fast addition & removal at the beginning of List #373
    2. Use ListBuffer if appending to end of the list is needed
  2. Array
  3. ListBuffer
    1. Use this when an element is needed to be appended (Is Constant Time) to end of list
  4. ArrayBuffer

Monday, September 12, 2016

List Example : Cons Operator, Nil & More...

scala> // #81

scala> // 'List' is Immutable Where as 'Array' is Mutable

scala> // For Mutable List, use ListBuffer #83

scala>

scala> /* List Operators
     |      :::  Append 2 lists
     |      ::   Cons Operator : Used to Prepend a New Element to
     |                           an existing List
     |                         : Is Constant Time
     |       :+  / append : Used to append an element to the List
     |                   : Is Linear Time #83
     | */
     | val l1 = List()  //Empty List
l1: List[Nothing] = List()

scala> val l2 = Nil     //Empty List (Can also be indicated by Nil)
l2: scala.collection.immutable.Nil.type = List()

scala> val l3 = List("maths", "english")
l3: List[String] = List(maths, english)

scala> //Using Cons (::) Operator

scala> //Note here '::' is a method of its right operand #85

scala> // Breadcrumb : Operator Associativity

scala> val l4 = "maths1" :: "english1" :: Nil
l4: List[String] = List(maths1, english1)

scala> val l5 = l3 ::: l4
l5: List[String] = List(maths, english, maths1, english1)

scala>

scala>

scala> /*
     | Useful List methods #85
     | */
     | val l1 = List("english", "math", "Science", "History", "Geo")
l1: List[String] = List(english, math, Science, History, Geo)

scala> l1.length
res53: Int = 5

scala> l1.count()
<console>:9: error: not enough arguments for method count: (p: String => Boolean)Int.
Unspecified value parameter p.
              l1.count()
                      ^

scala> l1.count(x => !x.equals("math"))
res55: Int = 4

scala> l1.head
res56: String = english