Question | Click to View Answer |
Use a builder to create |
val b = Array.newBuilder[Int]
b += 10
b += 20
|
Use a factory method to create |
|
Combine |
|
Multiple every element in |
|
Remove the even numbers from |
|
Grab the first two elements from |
|
Remove the first two elements from |
|
Create an array with the elements from index positions 1 through 4 from |
|
Create an array with the unique elements in |
|
Find the first even value that's greater than four in this array |
val arr = Array(1, 2, 3, 4, 5, 6, 7, 8)
arr.find(i => i % 2 == 0 && i > 4) // Some(6)
|
Find the even values greater than 10 in |
val arr = Array(1, 2, 3)
arr.find(i => i % 2 == 0 && i > 10) // None
|
Return true if |
val arr = Array(1, 2, 3)
arr.exists(i => i > 1) // true
|
Return false if |
val arr = Array(1, 2, 3)
arr.exists(i => i < 0) // false
|
Convert |
|
Convert |
Array("a", "b", "c").mkString("{", ",", "}")
|
Sum all the elements in |
val arr = Array(1, 2, 3, 4)
arr.foldLeft(0)((memo, y) => memo + y)
|
Multiply all the elements in |
val arr = Array(1, 2, 3, 4)
arr.foldLeft(1)((memo, y) => memo * y)
|
Multiply all the elements in |
val arr = Array(1, 2, 3, 4)
arr.foldLeft(1)(_ * _) // 24
|
Add all the elements in |
var total = 0
for (i <- Array(1, 2, 3, 4)) total += i
total // 10
|
Explain the problem with the following code: val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
val res = arr.map(_ + 1).filter(_ % 2 == 0).slice(1, 3)
res // Array(4, 6)
Refactor the code so it's better. |
This code is inefficient because it creates intermediate collections that are immediately thrown away.
You can avoid unnecessarily creating intermediate collections with val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
val res = arr.view.map(_ + 1).filter(_ % 2 == 0).slice(1, 3).to(Array)
res // Array(4, 6)
You only need to worry about this when your collections are large enough to create a performance bottleneck. |
Convert |
Array(1, 2, 3).to(Vector)
|
Convert |
Vector(1, 2, 3).to(Array)
|
Convert |
Array(1, 1, 2, 2, 3, 3).to(Set) // Set(1, 2, 3)
Notice how the set does not include any duplicate values. |