Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator delete in scala

Tags:

java

scala

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();
    }
}
like image 819
Suzy Tros Avatar asked Jan 20 '26 04:01

Suzy Tros


2 Answers

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.

like image 179
Andrey Tyukin Avatar answered Jan 21 '26 20:01

Andrey Tyukin


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)
like image 27
SimY4 Avatar answered Jan 21 '26 22:01

SimY4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!