When applying a filter to a scala map, how can I also check which records have been deleted?

I am learning scala and at some point I want to remove entries from the map based on value (not key). I also want to know how many records have been deleted - my program expects only one record to be deleted. Deleting records based on their values ​​can be done by applying filterNot, ok - but how can I check that only one record is deleted?

So far, the only way I've seen this is to run the predicate twice - once for the "count" method (to count how often the predicate matches) and then with filterNot to actually delete the records.

What's Scala's way of achieving this in one go?

The only other solution I have found is to first use a filter (...) to get the values ​​to be removed and then use "-" to throw out the items by their keys, but again this requires two passes.

+3


source to share


3 answers


As long as you don't mind creating a collection from the deleted information, you can use partition

:



scala> Map(1 -> 1, 2 -> 2, 3 -> 3)
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> res0.partition { case (k, v) => v % 2 == 0 }
res3: (Map(2 -> 2),Map(1 -> 1, 3 -> 3))

      

+7


source


If you just want to know if only one record has been deleted, you can use size to get the size before and after the filter operation. There should be one difference.



scala> Map(1 -> 1, 2 -> 2, 3 -> 3)
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> res0.filterNot { case (k, v) => v % 2 == 0 }
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 3 -> 3)

scala> res0.size - res1.size
res2: Int = 1

      

+5


source


Consider groupBy

the displayed values ​​as follows; let be

val a = ((1 to 3) zip (11 to 33)).toMap
a: Map(1 -> 11, 2 -> 12, 3 -> 13)

      

then

a.groupBy(_._2 % 2 == 0)
res: Map(false -> Map(1 -> 11, 3 -> 13), true -> Map(2 -> 12))

      

0


source







All Articles