C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: We need to specify the type of elements as part of the List.newBuilder function call. Here I use Int.
And: We can add elements to the Builder's internal buffer by using the addition operator. With result() we get the final immutable list.
Scala program that uses List.newBuilder
// Create a list with values.
val numbers = List(10, 11, 12)
println(numbers)
// Create a list with a Builder.
val builder = List.newBuilder[Int]
builder += 10
builder += 11
builder += 12
val numbers3 = builder.result()
println(numbers3)
Output
List(10, 11, 12)
List(10, 11, 12)
Scala program that combines two lists
// Add two lists together.
val numbers1 = List(13, 14)
val numbers2 = List(15, 16)
val numbers3 = numbers1 ::: numbers2
println(numbers3)
Output
List(13, 14, 15, 16)
Warning: If we use "::" with another list, that entire list (not its individual elements) will be placed in the head of the new list.
Scala program that initializes list with new element
// Initialize a list by placing an element at its start.
val numbers1 = List(100, 200)
val numbers2 = 50 :: numbers1
println(numbers2)
Output
List(50, 100, 200)
Scala program that uses List.empty
// Initialize an empty list and add an element to it.
val numbers1 = List.empty[String]
val numbers2 = "cat" :: numbers1
println(numbers2)
Output
List(cat)