Tutorial by Examples

Supposing the following list we can sort a variety of ways. val names = List("Kathryn", "Allie", "Beth", "Serin", "Alana") The default behavior of sorted() is to use math.Ordering, which for strings results in a lexographic sort: names.sorted /...
To create a collection of n copies of some object x, use the fill method. This example creates a List, but this can work with other collections for which fill makes sense: // List.fill(n)(x) scala > List.fill(3)("Hello World") res0: List[String] = List(Hello World, Hello World, Hello...
It is now a best-practice to use Vector instead of List because the implementations have better performance Performance characteristics can be found here. Vector can be used wherever List is used. List creation List[Int]() // Declares an empty list of type Int List.empty[Int] // U...
Note that this deals with the creation of a collection of type Map, which is distinct from the map method. Map Creation Map[String, Int]() val m1: Map[String, Int] = Map() val m2: String Map Int = Map() A map can be considered a collection of tuples for most operations, where the first e...
Map 'Mapping' across a collection uses the map function to transform each element of that collection in a similar way. The general syntax is: val someFunction: (A) => (B) = ??? collection.map(someFunction) You can provide an anonymous function: collection.map((x: T) => /*Do something wi...
The Scala Collections framework, according to its authors, is designed to be easy to use, concise, safe, fast, and universal. The framework is made up of Scala traits that are designed to be building blocks for creating collections. For more information on these building blocks, read the official S...
The fold method iterates over a collection, using an initial accumulator value and applying a function that uses each element to update the accumulator successfully: val nums = List(1,2,3,4,5) var initialValue:Int = 0; var sum = nums.fold(initialValue){ (accumulator,currentElementBeingIterated...
foreach is unusual among the collections iterators in that it does not return a result. Instead it applies a function to each element that has only side effects. For example: scala> val x = List(1,2,3) x: List[Int] = List(1, 2, 3) scala> x.foreach { println } 1 2 3 The function sup...
The reduce(), reduceLeft() and reduceRight methods are similar to folds. The function passed to reduce takes two values and yields a third. When operating on a list, the first two values are the first two values in the list. The result of the function and the next value in the list are then re-appli...

Page 1 of 1