30 Working with List: element selection

 

After reading this lesson, you will be able to:

  • Select the first element of a sequence.
  • Pick the nth item of a list.
  • Find the first element of a sequence that respects a given predicate.
  • Find the minimum/maximum item in a list according to some criteria.

In the previous lesson, you have learned how to analyze the properties of a sequence. In this lesson, you’ll discover how to select one item in a list by its position. You’ll also learn how to find an item that has specific characteristics. Finally, you’ll see how to select the minimum or maximum element in a list based on natural ordering or custom ordering criteria. In the capstone, you’ll analyze the Movies Dataset to determine which movie has the highest profit.

30.1  Selecting an element by its position

Let’s continue to expand the functionalities of your address book program, in which each contact is represented as the following:

Listing 30.1: Representation of 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)

30.2  Finding an element with given features

30.3  Picking the minimum or maximum item

30.4  Summary

30.5  Answers to Quick Checks