11.26. Using Sortable Sets

Problem

You want to be able to store and retrieve items from a set in a sorted order.

Solution

To retrieve values from a set in sorted order, use a SortedSet. To retrieve elements from a set in the order in which elements were inserted, use a LinkedHashSet.

A SortedSet returns elements in a sorted order:

scala> val s = scala.collection.SortedSet(10, 4, 8, 2)
s: scala.collection.SortedSet[Int] = TreeSet(2, 4, 8, 10)

scala> val s = scala.collection.SortedSet("cherry", "kiwi", "apple")
s: scala.collection.SortedSet[String] = TreeSet(apple, cherry, kiwi)

A LinkedHashSet saves elements in the order in which they were inserted:

scala> var s = scala.collection.mutable.LinkedHashSet(10, 4, 8, 2)
s: scala.collection.mutable.LinkedHashSet[Int] = Set(10, 4, 8, 2)

Discussion

The SortedSet is available only in an immutable version. If you need a mutable version, use the java.util.TreeSet. The LinkedHashSet is available only as a mutable collection.

The examples shown in the Solution work because the types used in the sets have an implicit Ordering. Custom types won’t work unless you also provide an implicit Ordering. For example, the following code won’t work because the Person class is just a basic class:

class Person (var name: String)

import scala.collection.SortedSet
val aleka = new Person("Aleka")
val christina = new Person("Christina")
val molly = new Person("Molly")
val tyler = new Person("Tyler")

// this won't work
val s = SortedSet(molly, tyler, christina, aleka)

In the ...

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.