How to combine filter and map in Scala?

后端 未结 6 606
不知归路
不知归路 2020-12-28 13:10

I have List[Int] in Scala. The List is List(1,2,3,4,5,6,7,8,9,10). I want to filter the list so that it only has even numbers. And I w

6条回答
  •  梦谈多话
    2020-12-28 13:57

    A for comprehension (which internally unfolds into a combination of map and withFilter) as follows,

    for (x <- xs if x % 2 == 0) yield x*2
    

    Namely

    xs.withFilter(x => x % 2 == 0).map(x => x*2)
    

提交回复
热议问题