val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6) val newList = l.map(x => x * 3)
Another useful function is filter. Filter is like map, in that it traverses every element in the list. However, filter will return a new list where all of the elements in the original list hold true for a particular predicate/test. For example, if we wanted to filter out all odd integer values in a list, we can write the following in Scala.
val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6) val newList = l.filter(x => (x %2 == 0))
Of course, we can combine both map and filter. Here's an example.
val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6) val newList = l.map(x => x * 3).filter(x => (x % 2) == 0)
No comments:
Post a Comment