Introduction to Scala Part2 : Collections

Bubu
710 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Traversable: Map operations Next: Traversable: Folds

Traversable: Sub-collection retrieval operations

  • Operations:
    • tail,
    • init,
    • slice,
    • take,
    • drop,
    • takeWhile,
    • dropWhile,
    • filter,
    • filterNot,
    • withFilter.
  • Goal: return some sub-collection identified by an index range or some predicate.
> List(1,2,3,4,5).tail
res1: List[Int] = List(2, 3, 4, 5)

> List(1,2,3,4,5).init
res2: List[Int] = List(1, 2, 3, 4)

> List(1,2,3,4,5).take(2)
res3: List[Int] = List(1, 2)

> List(1,2,3,4,5).dropWhile(x => x < 3)
res4: List[Int] = List(3, 4, 5)


> List(1,2,3,4,5).filter(x => x %2  == 0)
res5: List[Int] = List(2, 4)

What about withFilter ?

> List(1,2,3,4,5).withFilter(x => x %2  == 0)
res6: scala.collection.generic.FilterMonadic[Int,List[Int]] = scala.collection.TraversableLike$WithFilter@550fa96f

> List(1,2,3,4,5).withFilter(x => x %2  == 0).map(x => x)
res7: List[Int] = List(2, 4)
return the tail of a list
return the init of a list
return a list of the n first elements of l
return the list without the first n elements
return the ood elements of the list
return the even elements of the list
take longest prefix of elements that satisfy a predicate.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content