How to filter a map in Scala

3 Answers

0 votes
val myMap = Map(1 -> "AA", 2 -> "BA", 3 -> "CO", 4 -> "BOB")

val filteredMap = myMap.filter { case (key, value) => key > 1 && value.startsWith("B") }

println(filteredMap) 
 
 
 
/*
run:
  
Map(2 -> BA, 4 -> BOB)
  
*/

 



answered Aug 8, 2025 by avibootz
0 votes
val myMap = Map(1 -> "AA", 2 -> "BA", 3 -> "CO", 4 -> "BOB")

val filteredByKey = myMap.filter { case (key, _) => key > 1 }

println(filteredByKey) 

 
 
/*
run:
  
Map(2 -> BA, 3 -> CO, 4 -> BOB)
  
*/

 



answered Aug 8, 2025 by avibootz
0 votes
val myMap = Map(1 -> "AA", 2 -> "BA", 3 -> "CO", 4 -> "BOB")

val filteredByValue = myMap.filter { case (_, value) => value.contains("O") }

println(filteredByValue) 

 
 
/*
run:
  
Map(3 -> CO, 4 -> BOB)
  
*/

 



answered Aug 8, 2025 by avibootz

Related questions

3 answers 92 views
1 answer 93 views
1 answer 78 views
1 answer 77 views
3 answers 214 views
...