Key filtering when repeating through a card

What is the best way to iterate over a map and filter out certain keys? Pseudocode may be something like

map.foreach(tuple where !list.contains(tuple._1) => { }) 

Thanks Bruce

+4
source share
3 answers
 val m = Map(1 -> "a", 2 -> "b", 4 -> "c", 10 -> "d") val s = Set(1,4) m.filterKeys { s.contains(_) == false } // Map(2 -> b, 10 -> d) 

But, if it is a huge card and a huge set, I would suggest to sort them first and mutually repeat through them, choosing the bits you need. Repeated calls to contains may not work as you would like, especially if you use List instead of Set .

+10
source
 map.withFilter{tuple => !list.contains(tuple._1)}.foreach{whatever} 

Equivalent

 for(tuple <- map if !list.contains(tuple._1)) whatever 
+4
source

This question has been asked and answered before :

Using the fact that Set[A] is a function of A => Boolean , you can simply do:

 map filterKeys s 
+4
source

Source: https://habr.com/ru/post/1398863/


All Articles