10.3. Choosing a Collection Method to Solve a Problem

Problem

There is a large number of methods available to Scala collections, and you need to choose a method to solve a problem.

Solution

The Scala collection classes provide a wealth of methods that can be used to manipulate data. Most methods take either a function or a predicate as an argument. (A predicate is just a function that returns a Boolean.)

The methods that are available are listed in two ways in this recipe. In the next few paragraphs, the methods are grouped into categories to help you easily find what you need. In the tables that follow, a brief description and method signature is provided.

Methods organized by category

Filtering methods

Methods that can be used to filter a collection include collect, diff, distinct, drop, dropWhile, filter, filterNot, find, foldLeft, foldRight, head, headOption, init, intersect, last, lastOption, reduceLeft, reduceRight, remove, slice, tail, take, takeWhile, and union.

Transformer methods

Transformer methods take at least one input collection to create a new output collection, typically using an algorithm you provide. They include +, ++, , −−, diff, distinct, collect, flatMap, map, reverse, sortWith, takeWhile, zip, and zipWithIndex.

Grouping methods

These methods let you take an existing collection and create multiple groups from that one collection. These methods include groupBy, partition, sliding, span, splitAt, and unzip.

Informational and mathematical methods

These methods provide information ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.