Scala collection – Arrays

 275 total views,  1 views today

Welcome to Scala series. In this tutorial, you will learn about Scala collection – Arrays.

Scala collection array

Array is a special type of collection which is used to store the fixed length of data. It is similar to Java Array. If you are a java programmer, then understanding scala array would be simpler.

To declare array of integers and String in Scala

Array[String]
Array[Integer]

In Java, we will declare the same arrays as,

int[]
String[]

Let us see an example for each Scala collection – arrays operations.

Creating a Scala array with fixed length

var arr = new Array[String](10)

In the above code, I have created an Array of String with the length of 10.

Creating a Scala array with values

 var arr = Array("a","b","c","d")

Adding elements to the array

arr(0) = "a";
arr(1) = "b";
arr(2) = "c";
arr(3) = "d";

Accessing elements of the array

println(arr(1))
println(arr(2))
println(arr(7))

Output

b
c
null

Iterate the array using foreach

 arr.foreach(println)

Output

a
b
c
d
null
null
null
null
null
null

Iterate the array using for loop

for (i <- arr) {
   println(i)
}

Get Array Length

arr.length

Update the value of the particular index

println(arr(1))
//Update the aray
arr.update(1, "xyz")

println(arr(1))

Array Filter function

object Scala {
  def main(args: Array[String]): Unit = {

    var arr = new Array[String](4)

    arr(0) = "a";
    arr(1) = "b";
    arr(2) = "c";
    arr(3) = "d";

    arr = arr.filter(i => i.equalsIgnoreCase("a"))
    
    arr.foreach(println)
  }
}

Output

a

Array Map function

object Scala {
  def main(args: Array[String]): Unit = {

    var arr = new Array[String](4)

    arr(0) = "a";
    arr(1) = "b";
    arr(2) = "c";
    arr(3) = "d";

    arr.map(i => i + i).foreach(println)
  }
}

Output

aa
bb
cc
dd

If you like to learn more about Scala collections please check out my other posts listed below.

  1. Scala List
  2. Scala Set
  3. Scala Stack
  4. Scala Queue

Please read Scala mutable and immutable collections if you like 🙂

References: https://docs.scala-lang.org/overviews/collections/arrays.html

Thanks for reading and hope you like this tutorial. Please leave a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.