In Scala, a List
is a fundamental data structure that represents an ordered collection of elements. Lists are immutable, which means that once a list is created, its elements cannot be changed. Here are some common operations you can perform on Scala lists:
1. Creating Lists:
You can create a list in Scala using the List
companion object:
scalaval myList: List[Int] = List(1, 2, 3, 4, 5)
2. Accessing Elements:
You can access elements in a list using their indices:
scalaval firstElement = myList(0) // Returns 1 val secondElement = myList(1) // Returns 2
3. Concatenation:
You can concatenate two lists using the ++
operator:
scalaval anotherList: List[Int] = List(6, 7, 8) val combinedList = myList ++ anotherList // Returns List(1, 2, 3, 4, 5, 6, 7, 8)
4. Adding Elements:
You can add elements to the beginning of a list using ::
(cons) operator:
scalaval newList = 0 :: myList // Returns List(0, 1, 2, 3, 4, 5)
5. List Operations:
head: Returns the first element of the list.
scalaval first = myList.head // Returns 1
tail: Returns the list without the first element.
scalaval rest = myList.tail // Returns List(2, 3, 4, 5)
isEmpty: Checks if the list is empty.
scalaval empty = myList.isEmpty // Returns false
6. Filtering:
You can filter elements based on a condition:
scalaval filteredList = myList.filter(_ > 2) // Returns List(3, 4, 5)
7. Mapping:
You can apply a function to each element in the list:
scalaval squaredList = myList.map(x => x * x) // Returns List(1, 4, 9, 16, 25)
8. Folding:
Folding allows you to reduce the elements of a list to a single value:
scalaval sum = myList.foldLeft(0)(_ + _) // Returns 15 (sum of all elements)
9. Sorting:
You can sort a list using the sorted
method:
scalaval sortedList = myList.sorted // Returns List(1, 2, 3, 4, 5)
These are just a few examples of the operations you can perform on Scala lists. Scala provides a rich set of methods for working with lists, and you can combine these operations to perform more complex tasks efficiently.
Comments
Post a Comment