Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip appending some condition in map scala?

I have a situation in which I need to create a map from a collection by applying some filter inside like given in the code below:

//Say I have a list
//I don't have to apply filter function ...

val myList = List(2,3,4,5)

val evenList = myList.map(x=>{
if ( x is even) x
else 0
}
//And the output is : List(2,0,4,0)
//The output actually needed was List(2,4) without applying filter on top like - ```myList.filter```
//I have objects instead of numbers of a case class so the output becomes :List(object1, None, object2, None)
But actual output needed was : List(object1,object2)

//The updated scenario

val basket = List(2,4,5,6)
case class Apple(name:Option[String],size:Option[Int])

val listApples: List[Apple] = basket.map(x=>{

  val r = new scala.util.Random
  val size = r.nextInt(10)

  if(x%2!=0){
    Apple(None,None)
  }
  else Apple(Some("my-apple"),Some(size))
})

Current Output :

Apple(Some(my-apple),Some(2))
Apple(Some(my-apple),Some(0))
Apple(None,None)
Apple(Some(my-apple),Some(4))
Expected was :
Apple(Some(my-apple),Some(2))
Apple(Some(my-apple),Some(0))
Apple(Some(my-apple),Some(4))
like image 276
supernatural Avatar asked Sep 27 '19 06:09

supernatural


1 Answers

I believe collect best suits your case. It takes a partial function as an argument and only if that function matches then the element is transformed and added to result:

val myList = List(2,3,4,5)

case class Wrapper(i: Int)

val evenList = myList.collect{
  case x if x % 2 == 0 => Wrapper(x)
}

In this case only 2 and 4 will be wrapped inside Wrapper:

List(Wrapper(2), Wrapper(4))
like image 140
Krzysztof Atłasik Avatar answered Oct 16 '22 05:10

Krzysztof Atłasik