Tuesday, 5 July 2016

Scala List Operation

Given a list: val list1 = List(1,3,4,0,-1,6)

1. Filter
The filter operator takes as operands a list of type List[T] and one function of type T => Boolean called predicate. This operator returns a new list with all elements of the original list for which the predicate is true.

scala> val list2 = list1 filter (_ > 0)
res0: List[Int] = List(1, 3, 4, 6)

2. Find
Returns the first element for which the predicate is true.

scala> list1 find (_ > 0)
res1: Option[Int] = Some(1)

3. Partition
The partition operator returns a pair of lists. The first one includes all elements that satisfies the predicate.

scala> list1 partition (_ > 0)
res3: (List[Int], List[Int]) = (List(1, 3, 4, 6),List(0, -1))

4. TakeWhile
The takeWhile operator iterates the list until it finds one element that doesn’t satisfy the predicate.
It returns the longest prefix such that every element satisfies the predicate.

scala> list1 takeWhile (_ > 0)
res4: List[Int] = List(1, 3, 4)

5. DropWhile
The dropWhile operator iterates the list until it finds one element that doesn’t satisfy the predicate,
It drops the longest prefix such that every element satisfies the predicate.

scala> list1 dropWhile (_ > 0)
res5: List[Int] = List(0, -1, 6)

6. Convert List[Option[T]] to List[T]
There is an implicit conversion from Option[A] to Iterable[A].

scala> val list1 = List(Some(1), None, Some(2))
scala> val list2 = list1.flatten
res5: List[Int] = List(1,2)

7. Pattern Matching
Match the list with unknown length.


object Names {
    def unapplySeq(name: String): Option[(String, String, Seq[String])] = {
        val names = name.trim.split("")
        if (names.size < 2) None
        else Some((names.last, names.head, names.drop(1).dropRight(1)))
    }
}


def greet(fullName: String) = fullName match {
    case Names(lastName, firstName, _*) = firstName + " " + lastName
    case _ = "Welcome"
}




No comments:

Post a Comment