Scala filter and map

You can filter the items in a collection to create a new collection that contains only the elements that match your filtering criteria.

In the below example, we create a list of even numbers from an input list. Also a list that contains numbers > 5

package com.scala.test

object TestFilter {

def main(args: Array[String]) {
val x = List.range(1, 10)
val evens = x.filter(_ % 2 == 0)
val greaterthan5 = x.filter(_ > 5)
println(evens)
println(greaterthan5)
}

}

Output
List(2, 4, 6, 8)
List(6, 7, 8, 9)

filterNot:

The filterNot method is similar to the filter method except that it will create a new collection with elements that do not match the predicate function.

package com.scala.test

object TestFilter {

def main(args: Array[String]) {
val x = List.range(1, 10)
val odds = x.filterNot (_ % 2 == 0)
val lessthan5 = x.filterNot(_ >= 5)
println(odds)
println(lessthan5)
}

}

Output
List(1, 3, 5, 7, 9)
List(1, 2, 3, 4)

Note: filter  and filterNot doesn’t modify the collection it’s invoked on

Combining filter, sort and map

package com.scala.test

case class Person(name: String, age: Int)

object TestFilterMap {
def main(args: Array[String]) {
val gyan = Person(“Gyan”, 30)
val rajesh = Person(“Rajesh”, 35)
val vivek = Person(“Vivek”, 25)
val guru = Person(“Guru”, 28)
val rochit = Person(“Rochit”, 27)
val praveen = Person(“Praveen”, 32)
val persons = List(gyan, rajesh, vivek, guru, rochit, praveen)
println(persons.filter(_.age > 28).sortBy(_.age).map(_.name))
}

}

Output
List(Gyan, Praveen, Rajesh)

Maps: filterKeys

When working with a mutable or immutable map, you can use a predicate with the filterKeys methods to define which map elements to retain. When using this method, remember to assign the filtered result to a new variable.

package com.scala.test

object FilterTest {
def main(args: Array[String]) {
var x = Map(1 -> “a”, 2 -> “b”, 3 -> “c”)
val y = x.filterKeys(_ > 2)
println(y)
}

}

Output
Map(3 -> c)

Mutable Map

1. retain method: it modifies a mutable map

We can filter the elements in a mutable map using the retain method to specify which elements should be retained.

package com.scala.test

object FilterTest {
def main(args: Array[String]) {
var x = collection.mutable.Map(1 -> “a”, 2 -> “b”, 3 -> “c”)
x.retain((k,v) => k > 1)
println(x)
}

}

Output
Map(2 -> b, 3 -> c)

2. transform method: the transform method doesn’t filter a map, but it lets you transform the elements in a mutable map.

package com.scala.test

object FilterTest {
def main(args: Array[String]) {
var x = collection.mutable.Map(1 -> “a”, 2 -> “b”, 3 -> “c”)
x.transform((k,v) => v.toUpperCase)
println(x)
}

}

Output
Map(2 -> B, 1 -> A, 3 -> C)

Leave a Reply

Your email address will not be published. Required fields are marked *