32 Working with List: Sorting and other operations

 

After reading this lesson, you will be able to

  • Sort a list
  • Produce a string representation of a sequence
  • Sum all the numerical elements of a list
  • Group items according to given criteria

In the previous lesson, you mastered how to filter elements of a sequence. In this lesson, you’ll learn about a variety of operations you can perform on lists. You’ll discover different approaches to sorting the items of a sequence. Also, you’ll learn how to produce a text representation for it. Finally, you’ll see how to restructure your list into a dictionary-like structure that groups elements with common features. In the capstone, you’ll use these operations to rank the films in the movies data set and display your data analysis in a human-readable form.

32.1 Sorting elements

In this unit, you have developed a software program to manage an address book to represent each contact.

Listing 32.1 Representing a contact
case class Contact(name: String,
                   surname: String,
                   numbers: List[ContactNumber],
                   company: Option[String],
                   email: Option[String])
 
sealed trait Label
case object Work extends Label
case object Home extends Label
 
case class ContactNumber(number: String, label: Label)

32.2 Converting a list to a string

32.3 Sum elements of numerical sequences

32.4 Grouping elements by feature

Summary

Answers to quick checks