benroth benroth - 2 months ago 4
Scala Question

scala duplicate elements in list

I need to duplicate every element in a list.
Here is what I came up with for that:

List.range(1,5).map(i => List(i,i)).flatten

which outputs

List[Int] = List(1, 1, 2, 2, 3, 3, 4, 4)

I wonder whether this is the most efficient way to do that (ultimately it needs to run on a lot of data), given that for every element, a new list would be created.

(the above is on an int range, to keep the example simple)

Any suggestions?

m-z m-z

A more general solution would be something like:

def duplicate[T](list: List[T]): List[T] = list.flatMap(x => List[T](x, x))

Using immutable collections won't be all that efficient for very large data sets. A simple implementation using the mutable ListBuffer is already 10 times faster than the above (using a list with one million elements):

def duplicate[T](list: List[T]): List[T] = {

    val buffer = collection.mutable.ListBuffer[T]()

    list.foreach{ x =>
        buffer += x
        buffer += x


This uses a general technique of appending to a ListBuffer for performance, then converting to the immutable List at the end.