user6172474
user6172474

Reputation:

Condition in Scala Map method

In Python, I can easily create a new list by condition

list_1 = [1,2,3,4,5]
new_list = [e for e in list_1 if e>3]
# result [4,5]

But not the same story for Scala. I tried using map map method

var array_1 = Array(1,2,3,4,5)
var new_array = array_1.map(e => if(e>3) e)
// result: [undefined, undefined, undefined, 4, 5]

Is there any magic I dont know here? Thankful for helping me

Upvotes: 0

Views: 730

Answers (3)

BlueSheepToken
BlueSheepToken

Reputation: 6099

map is just to apply a method to every element.

filter is to filter every element.

You can combine them doing a single collect with a Partial Function

Seq(0, 1, 2, 3, 4, 5).collect{
  case e if 3 < e => 2*e
}

Upvotes: 1

senjin.hajrulahovic
senjin.hajrulahovic

Reputation: 3191

The solution which @Mario suggested is the preferred way to achieve this in scala.

Anyway, you can also achieve this by using a for comprehension which is similar to the way it's done in python:

for {e <- array_1; if e > 3} yield e

This code get desugared to a filter method invocation.

Upvotes: 3

Mario Galic
Mario Galic

Reputation: 48420

Try filter like so

var new_array = array_1.filter(e => e > 3)

which outputs

new_array: Array[Int] = Array(4, 5)

Upvotes: 4

Related Questions