Back
Close

Introduction to Scala Part2 : Collections

Bubu
724 views
Previous: Traversable: Folds

Traversable: Subdivision operations

  • Operations: splitAt, span, partition, groupBy
  • Goal: split the elements of this collection into several sub-collections.
> List(1,2,3,4,5).splitAt(3)
res0: (List[Int], List[Int]) = (List(1, 2, 3),List(4, 5))

Tuple2 type: (List[Int], List[Int]) = Tuple2[List[Int],List[Int]]

TupleN[T1,..,Tn](_1: T1, _2: T2, ..., _n: Tn)

val t = new Tuple2[Int,Int](2, 3)
// a short hand is:
val t = (2, 3)

// To access values:
t._1 // 2
t._2 // 3
> List(1,3,2,5,4).span(x => x < 3) // put all element in one list until predicate is false, from that point it puts all the elements in the second list
res1: (List[Int], List[Int]) = (List(1),List(3, 2, 5, 4))

scala> List(1,3,2,5,4).partition(x => x < 3) // put all element that valid the predicate in one list and the others in a second list
res2: (List[Int], List[Int]) = (List(1, 2),List(3, 5, 4))

> val l = List(1,3,2,5,4).map(x => if(x % 2 == 0) ("even", x) else ("odd", x)) 
l: List[(String, Int)] = List((odd,1), (odd,3), (even,2), (odd,5), (even,4))

scala> l.groupBy(x => x._1)
res3: scala.collection.immutable.Map[String,List[(String, Int)]] = 
Map(odd -> List((odd,1), (odd,3), (odd,5)), even -> List((even,2), (even,4)))
should split at position n
groupByHouse GoT characters
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
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants