Java Reference
In-Depth Information
Working with collections
Now that you've seen how to create collections, you need to know what you can do with them. It
turns out that collections in Scala support operations similar to what the Streams API provides.
For instance, you'll recognize filter and map in the following example and as illustrated in figure
15.1 :
Figure 15.1. Stream-like operations with Scala's List
val fileLines = Source.fromFile("data.txt").getLines.toList()
val linesLongUpper
= fileLines.filter(l => l.length() > 10)
.map(l => l.toUpperCase())
Don't worry about the first line; it basically transforms a file into a list of strings consisting of
the lines in the file (similar to what Files.readAllLines provides in Java 8). The second line
creates a pipeline of two operations:
A filter operation that selects only the lines that have a length greater than 10
A map operation that transforms these long lines to uppercase
This code can be also written as follows:
val linesLongUpper
= fileLines filter (_.length() > 10) map(_.toUpperCase())
You use the infix notation as well as the underscore (_), which is a placeholder that's
positionally matched to any arguments. In this case you can read _.length() as l => l.length(). In
the functions passed to filter and map, the underscore is bound to the line parameter that is to
be processed.
There are many more useful operations available in Scala's collection API. We recommend
taking a look at the Scala documentation to get an idea. [ 4 ] Note that it's slightly richer than what
 
Search WWH ::




Custom Search