Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out keys while iterating through a map

What's the best way to iterate through a map, and filter out certain keys? The pseudocode might be something like

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

Thanks Bruce

like image 869
Bruce Ferguson Avatar asked Dec 02 '22 23:12

Bruce Ferguson


1 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 this is a huge map and a huge set, then I'd suggest sorting them first and mutually iterating through them, picking off the bits that you need as you go. The repeated calls to contains may not perform as well as you'd like, especially if you use a List instead of a Set.

like image 163
Derek Wyatt Avatar answered Dec 18 '22 10:12

Derek Wyatt