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