'How to merge Scala Lists'에 해당되는 글 1건

  1. 2014.03.28 How to merge Scala Lists
00.scala2014. 3. 28. 13:37
반응형

Scala List FAQ: How do I merge Scala Lists?

There are at least three ways to merge/concatenate Scala List instances, as shown in the examples below.

1) The Scala List ::: method

First, you can merge two Scala lists using the ::: method of the List class, as demonstrated here at theScala command prompt:

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)

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

This operation is said to have O(n) speed, where n is the number of elements in the first List.

2) The Scala List concat method

You can also merge two Scala lists using the List class concat method:

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)

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

3) The Scala List ++ method

You can also use the List ++ method to concatenate Scala Lists, as shown here:

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)

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

I'll try to add more information on these three approaches as I learn about them, but for now, I just wanted to share these three approaches.

Posted by 1010