How to merge (concatenate) Lists in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.5, “How to Merge (Concatenate) Lists in Scala”

Problem

You want to merge/concatenate the contents of two lists.

Solution

Merge two lists using the ++, concat, or ::: methods. Given these two lists:

scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)

scala> val b = List(4,5,6)
b: List[Int] = List(4, 5, 6)

you can use the ++ method as shown in the following example. It’s used consistently across immutable collections, so it’s easy to remember:

scala> val c = a ++ b
c: List[Int] = List(1, 2, 3, 4, 5, 6)

If you work with the List class frequently, you may prefer using ::: as a way to create a new list from two existing lists:

scala> val c = a ::: b
c: List[Int] = List(1, 2, 3, 4, 5, 6)

The concat method on the List object also works:

scala> val c = List.concat(a, b)
c: List[Int] = List(1, 2, 3, 4, 5, 6)

Discussion

Perhaps because I come from a Java background, I don’t work with the List class too often, so I can’t remember some of its custom methods without looking at its Scaladoc. As a result, I prefer the ++ method, because it’s consistently used across immutable collections.

However, keep in mind what the List class is good at. As its Scaladoc states, “This class is optimal for last-in-first-out (LIFO), stack-like access patterns. If you need another access pattern, for example, random access or FIFO, consider using a collection more suited to this than List.” See Recipe 10.4, “Understanding the Performance of Collections” for a discussion of List class performance.

See Also

  • The List class

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.