Tuesday 1 September 2020

Scala: Arrays

Array is a collection of elements of same type.


Syntax

var/val variableName = new Array[dataType](size)

 

Example

var arr1 = new Array[Int](10)

val arr1 = new Array[Int](10)

 

Above statements define an array of integers all initialized with 0.

scala> val arr1 = new Array[Int](10)
val arr1: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

How to add elements to array?

You can add elements to the array using an index. For example, arr1(0) is used to access the element at index 0.

 

arr1(0) = 10

Above statement initialize 0th index with value 10.

scala> arr1(0) = 10

scala> arr1(1) = 23

scala> arr1
val res115: Array[Int] = Array(10, 23, 0, 0, 0, 0, 0, 0, 0, 0)

Define array using Array() function

You can even define an array using Array() function.

scala> val arr2 = Array("One", "Two", "Three")
val arr2: Array[String] = Array(One, Two, Three)

As you see above snippet, Scala infers the type of array based on the content.

scala> val arr3 = Array("One", 2, 3, 123.45, true)
val arr3: Array[Any] = Array(One, 2, 3, 123.45, true)

In the above example, array contains string, int, double and boolean values, so Scala take supertype of all these types which is Any.

 

Find the sum of elements of an array?

‘sum’ function is used to get the sum of all the elements of the array.

scala> Array(2, 3, 5, 7).sum
val res153: Int = 17

Find the maximum element in an array

Use the ‘max’ function.

scala> Array(2, 30, 51, 7).max
val res155: Int = 51

Sort the elements of array

Use the ‘sorted’ function. This method does not sort in place, it return a completely new array with sorted data.

scala> var arr1 = Array(2, 30, 51, 7)
var arr1: Array[Int] = Array(2, 30, 51, 7)

scala> var arr2 = arr1.sorted
var arr2: Array[Int] = Array(2, 7, 30, 51)

scala> arr1
val res166: Array[Int] = Array(2, 30, 51, 7)

scala> arr2
val res167: Array[Int] = Array(2, 7, 30, 51)

Reverse the elements of array

Use ‘reverse’ function to reverse the elements of the array. This method does not reverse in place, it return a completely new array with reversed data.

scala> var arr1 = Array(2, 30, 51, 7)
var arr1: Array[Int] = Array(2, 30, 51, 7)

scala> var arr2 = arr1.reverse
var arr2: Array[Int] = Array(7, 51, 30, 2)

scala> arr1
val res169: Array[Int] = Array(2, 30, 51, 7) 

scala> arr2
val res170: Array[Int] = Array(7, 51, 30, 2)

Print elements of array

Use ‘mkString’ method to get the array elements as a string and separate each element with a given separator.

scala> var res = Array(2, 3, 5, 7).mkString(",")
var res: String = 2,3,5,7

scala> println(res)
2,3,5,7

Separate array elements using |.

scala> var res = Array(2, 3, 5, 7).mkString("|")
var res: String = 2|3|5|7

scala> println(res)
2|3|5|7



Previous                                                    Next                                                    Home

No comments:

Post a Comment