Introduction to Scala Part2 : Collections
Bubu
6,480 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Traversable: Map operations
- Operations:
- map,
- flatMap,
- collect
- collectFirst
- Goal: produce a new collection by applying some function to collection elements.
collect and collectFirst methods will be see in course C#03
Map
def map[B](f: (A) ⇒ B): Traversable[B]
Map is a HOF that builds a new collection by applying a function to all elements of this collection.
> List("John Snow", "Aria Stark", "Tyrion Lannister").flatMap(x => x.split(" "))
res0: List[String] = List(John, Snow, Aria, Stark, Tyrion, Lannister)
Split all the sentences in Lists of words
count the words in l
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package fp101.tp02.collections
object ExerciceMap {
/**
* Split all the sentences of a list l in lists of words
*
* e.g: splitInWords(List("Hi", "Hello World", "Look who it is"))
* should gives:
* List(List(Hi), List(Hello, World), List(Look, who, it, is))
*
* Hint: use Map
*/
def splitInWords(l: List[String]) = ???
/**
*
* Using flatMap, count the number of Words from a list of sentences,
* e.g: countWords(List("Hi", "Hello World", "Look who it is"))
* gives 7
*
*
*/
def countWords(l: List[String]) = ???
}
Enter to Rename, Shift+Enter to Preview