Skip to main content

Operations on list in Scala, Part - 1

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:

scala
val myList: List[Int] = List(1, 2, 3, 4, 5)

2. Accessing Elements:

You can access elements in a list using their indices:

scala
val firstElement = myList(0) // Returns 1 val secondElement = myList(1) // Returns 2

3. Concatenation:

You can concatenate two lists using the ++ operator:

scala
val 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:

scala
val newList = 0 :: myList // Returns List(0, 1, 2, 3, 4, 5)

5. List Operations:

  • head: Returns the first element of the list.

    scala
    val first = myList.head // Returns 1
  • tail: Returns the list without the first element.

    scala
    val rest = myList.tail // Returns List(2, 3, 4, 5)
  • isEmpty: Checks if the list is empty.

    scala
    val empty = myList.isEmpty // Returns false

6. Filtering:

You can filter elements based on a condition:

scala
val filteredList = myList.filter(_ > 2) // Returns List(3, 4, 5)

7. Mapping:

You can apply a function to each element in the list:

scala
val 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:

scala
val sum = myList.foldLeft(0)(_ + _) // Returns 15 (sum of all elements)

9. Sorting:

You can sort a list using the sorted method:

scala
val 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.




#blog #scala #coding #learning