C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Length: This property returns the number of elements in the list (its size). The "size" property is the same as length.
First, last: To access the first element, we use index zero. And for the last one, we use the list's length minus 1.
Tip: In Scala we find lists have many properties: we can use "head" for the first element or "last" for the last one—that style is clearer.
Scala program that creates String List
// Create a String List with 3 elements.
val names = List("cat", "bird", "fish")
// Print the list.
println(names)
// Print element count (the list size).
println(names.length)
// Access the first and then last elements.
val first = names(0)
println(first)
val last = names(names.length - 1)
println(last)
Output
List(cat, bird, fish)
3
cat
fish
Scala program that uses head, tail
// An Int list with three elements.
val ids = List(20, 80, 400)
println(ids)
// The head is the first element in the list.
val head = ids.head
println(head)
// The tail is a list of all elements except the first.
println(ids.tail)
println(ids.tail.length)
Output
List(20, 80, 400)
20
List(80, 400)
2
Here: We call map() on a string list. We call toUpperCase() on all elements, and the resulting list has uppercased color names.
Scala program that uses List map
// A list of strings.
val colors = List("blue", "yellow", "green")
// Use map to uppercase all strings in the list.
// ... The underscore is each variable encountered.
val result = colors.map(_.toUpperCase())
println(result)
Output
List(BLUE, YELLOW, GREEN)
Scala program that combines two lists
// Create two String lists.
val positions1 = List("top", "bottom")
val positions2 = List("left", "right")
println(positions1)
println(positions2)
// Combine the two lists with an operator.
val positions3 = positions1 ++ positions2
println(positions3)
Output
List(top, bottom)
List(left, right)
List(top, bottom, left, right)
Here: We provide a List of ids with indexes 0 through 4 inclusive. We take slices of this list.
Scala program that takes list slice
val ids = List(20, 21, 22, 23, 24)
// indexes:
// 0 = 20
// 1 = 21
// 2 = 22
// 3 = 23
// 4 = 24
// Take slice from index 2 until 4 (excludes 4).
val result1 = ids.slice(2, 4)
println(result1)
// Take slice from index 0 until 3.
val result2 = ids.slice(0, 3)
println(result2)
Output
List(22, 23)
List(20, 21, 22)
Tip: We unpack our tuple immediately after calling splitAt. This syntax form makes it easy to use the two resulting lists.
Scala program that splits list, uses splitAt
// This list contains four Booleans.
val list = List(true, false, true, true)
// Split this list at index 2 (before the third element).
// ... This returns a tuple containing two lists.
val (left, right) = list.splitAt(2)
// Print results of splitAt.
println(left)
println(right)
Output
List(true, false)
List(true, true)
Scala program that adds to start
val verbs1 = List("open", "search", "close", "sort")
// Add a string to the list's start.
val verbs2 = "mix" :: verbs1
// Print our lists.
println(verbs1)
println(verbs2)
Output
List(open, search, close, sort)
List(mix, open, search, close, sort)
Here: We have a lambda that uppercases, and then prints, each string in a list.
Scala program that uses foreach
// A list of four nouns (strings).
val nouns = List("computer", "box", "table", "wall")
// Call a lambda function on each element with foreach.
// ... Write uppercase strings to the screen.
nouns.foreach(x => println(x.toUpperCase()))
Output
COMPUTER
BOX
TABLE
WALL
Scala program that causes value update error
val names = List("cat", "bird", "dog")
// A list cannot be updated.
// ... This will not compile.
names(0) = "fish"
Output
error: value update is not a member of List[String]
names(0) = "fish"
^
one error found
Var: We use the "things" variable and bind it to one List. But then we can rebind it to another, separate list.
var, valScala program that uses var with list
// Create a variable list.
var things = List(10, 11, 15)
println(things)
// Change the variable binding.
things = List(16, 19, 200)
println(things)
Output
List(10, 11, 15)
List(16, 19, 200)
Thus: A List object itself is always unchangeable. But with var we can point to different lists with one variable.
Scala program that causes val error
val x = List(1.5, 2.5, 10.1)
// This will not compile.
// ... A val cannot be bound to a new object.
x = List(2.1, 2.5)
Output
error: reassignment to val
x = List(2.1, 2.5)
^
one error found
Tip: For simple collections, a list of tuples is more efficient than a map—iteration to find any element is always fast.
ForScala program that creates list of tuples
// Create a list of pairs (tuples with two items).
val pairs = List((10, "ten"), (20, "twenty"), (50, "fifty"))
// Loop over our pairs.
for (pair <- pairs) {
println(pair._1 + "..." + pair._2)
}
Output
10...ten
20...twenty
50...fifty
Instead: The list is frozen at creation-time. It is not changed, even when the var is reassigned. It contains values, not references.
Concept: A List, even when created based on variable data, is immutable. It is frozen in time once we create it.
Scala program that uses List, reassigns variable
// Two string variables.
var shape1 = "BOX"
var shape2 = "SPHERE"
// Create immutable list with variables in it.
val shapes = List(shape1, shape2)
// Change the variable.
// ... The value change is not reflected in the list.
shape1 = "CUBE"
println(shape1)
println(shape2)
println(shapes)
Output
CUBE
SPHERE
List(BOX, SPHERE)
Scala program that uses List as argument
// Receives a List argument.
def lengthDoubled(values: List[Int]) = values.length * 2
// Pass list to def as argument.
val shades = List(10, 0, 5)
val result = lengthDoubled(shades)
println(result)
Output
6
Here: We loop over two Lists at once. We use a for-loop with the until() method to iterate over all indexes in the List.
Scala program that loops over List with indexes
val list1 = List(10, 20, 30)
val list2 = List(11, 21, 31)
// Loop over all indexes in first list.
// ... Use until to stay in range of valid indexes.
for (i <- 0.until(list1.length)) {
// Access elements from both lists.
val element1 = list1(i)
val element2 = list2(i)
println(element1 + "/" + element2)
}
Output
10/11
20/21
30/31
Here: We call toUpperCase() on each string in a List. The resulting list is the same but has uppercase strings.
Scala program that uses map on list
// List of continent names.
val names = List("australia", "asia", "antarctica")
println(names)
// Use map to uppercase all strings.
// ... A new list is created.
val result = names.map { x => x.toUpperCase() }
println(result)
Output
List(australia, asia, antarctica)
List(AUSTRALIA, ASIA, ANTARCTICA)
Scala program that uses find
// A List with 3 items.
val languages = List("python", "scala", "java")
// Find an element that starts with this letter.
val result = languages.find { x => x.charAt(0) == 's' }
println(result.getOrElse("No s"))
// No items are found starting with this letter.
val result2 = languages.find(_.charAt(0) == 'z')
println(result2.getOrElse("No z"))
Output
scala
No z
But: Immutability has many advantages. To copy a list, can just reuse an existing list, as it will never change.
And: There are known security benefits to immutable objects. Threads (which become increasingly important in our world) also benefit.
Quote: By default, collection classes such as List and Map are immutable.... The implementation of these classes and their guarantees of immutability mean that the new instance can re-use existing nodes, which, especially in the case of creating copies, is very efficient.
Immutable object: Wikipedia