Back
Close

Introduction to Scala Part2 : Collections

Bubu
5,811 views
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.
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io