How can I convert this to scala since iterator has no remove method?
iter is defined like this:
Iterator<Integer> iter = cache.keySet().iterator();
where cache is a hashmap
while (iter.hasNext()) {
int num = iter.next();
if (!part.contains(num)){
iter.remove();
}
}
If your actual goal is to filter some keys from the cache, you can do this directly, without loops and iterators:
val cache = Map("a" -> 3, "b" -> 5, "c" -> 7)
val part = Set("x", "y", "b")
val filteredCache = cache.filter{ case (k, _) => part.contains(k) }
// prints `Map(b -> 5)`, because "a" and "c" not in `part`
println(filteredCache)
EDIT
As @SymY4 has absolutely rightly noted, filter and filterKeys behave quite differently: filter returns a new Map (immutable version), or filters the elements in-place (mutable version). However, filterKeys only constructs a filtered view of the original collection. Therefore, calling filterKeys repeatedly is not advisable, because it would stack more and more views on top of each other.
However, the solution with filter should still be valid.
Doing a lot of filters on a map will eventually make resulting map too slow. Because you'll need to apply all the filters you've added before you reach the actual cache store. I suggest to remove elements from a map by using -- syntax
scala> Map("a" -> 1, "b" -> 2, "c" -> 3)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)
scala> res0 -- Set("x", "y", "b")
res1: scala.collection.immutable.Map[String,Int] = Map(a -> 1, c -> 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With