treeset

How to use sortable Sets in Scala (SortedSet, TreeSet, LinkedHashSet)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.28, “How to Use Sortable Sets in Scala”

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:

How to create a mutable Set in Scala

Scala Set FAQ: How do I create a mutable Set in Scala?

To create a mutable set in Scala, first determine the type of set you want. You do this because the mutable Set is actually a trait, and you need to determine which concrete implementation you want.

For instance, if you want a SortedSet of String, define it like this:

val names = scala.collection.mutable.SortedSet[String]()

Then you can add elements to the set later like this:

Java mail IMAP list example - List all the email addresses in an IMAP mailbox

Java Mail (JavaMail) IMAP FAQ: Can you show me how to get a list of all the email addresses in an IMAP mailbox using the Java Mail API (JavaMail API)?

Sure. Here's the source code for a Java mail (JavaMail) program that extracts all of the "from" fields out of a specified mailbox. This works for both POP3 and IMAP mailboxes.

Before going to the code, note the cool use of a TreeSet (java.util.TreeSet) in this example. Based on our offline discussion, you mentioned that you really want is this: