Scala - collections in Scala

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-01 08:14:49 Viewed : 265


Scala provides a rich set of collection libraries that offer a wide range of data structures and methods for working with collections. Here are some common examples using collections in Scala:

1. Lists:

scala
// Creating a List val myList = List(1, 2, 3, 4, 5) // Accessing elements val firstElement = myList.head // 1 val restOfTheList = myList.tail // List(2, 3, 4, 5) // Adding elements val newList = myList :+ 6 // List(1, 2, 3, 4, 5, 6) // Mapping elements val doubledList = myList.map(_ * 2) // List(2, 4, 6, 8, 10)

2. Sets:

scala
// Creating a Set val mySet = Set(1, 2, 3, 4, 5) // Checking for element existence val containsThree = mySet.contains(3) // true // Adding elements val newSet = mySet + 6 // Set(1, 2, 3, 4, 5, 6) // Intersection of sets val otherSet = Set(4, 5, 6, 7, 8) val intersection = mySet.intersect(otherSet) // Set(4, 5, 6)

3. Maps:

scala
// Creating a Map val myMap = Map("Alice" -> 25, "Bob" -> 30, "Charlie" -> 22) // Accessing values val aliceAge = myMap("Alice") // 25 // Adding key-value pairs val newMap = myMap + ("David" -> 28) // Iterating through key-value pairs myMap.foreach { case (name, age) => println(s"$name is $age years old") }

4. Sequences:

scala
// Creating a Sequence val mySeq = Seq(1, 2, 3, 4, 5) // Concatenating sequences val combinedSeq = mySeq ++ Seq(6, 7, 8) // Filtering elements val evenNumbers = mySeq.filter(_ % 2 == 0) // Seq(2, 4)

5. Arrays:

scala
// Creating an Array val myArray = Array(1, 2, 3, 4, 5) // Accessing elements val thirdElement = myArray(2) // 3 // Updating elements myArray(0) = 10 // Converting to List val myList = myArray.toList

These examples cover some of the fundamental operations you can perform on collections in Scala. Scalas collections library is extensive and versatile, offering many more data structures and methods for various use cases.

Search
Related Articles

Leave a Comment: