Nili Al
Nili Al

Reputation: 21

Scala filter keys on composed key Map

I have a map with that structure:

key: an instance of a case class X

value: an instance of a case class Y

X composed of - a:String, b:String, c:String, d:Int (fields)

given b1, c1, d1, i want to filter the map by keys, when: a can be any string, b=b1, c=c1, d=d1.

means I want to get a map result as an instance of HashMap[X, Y], and filter X only on the 3 fields that I have (b1, c1, d1).

keys that I want can be for example: (a1,b1,c1,d2), (a2,b1,c1,d1)

I tried something like that:

      val resMap = givvenMap.filterKeys(key => {
        key.b == b1 && key.c == c1 && key.d == d1
      }).asInstanceOf[HashMap[X, Y]]

I need that the field "a" will be a part of the key in the given map. The map must be immutable!

What can I do?

Upvotes: 0

Views: 630

Answers (1)

Dima
Dima

Reputation: 40500

You DON'T need a HashMap. Just use Map. Other than that, your snippet seems fine, except for the nested pair of {..} which is completely redundant. Just get rid of it.

A little nicer way to write the same thing is this:

    givvenMap.filterKeys {
      case X(_, `b1`, `c1`, `d1`) => true
      case _ => false
    }

Note though that filterKeys is deprecated (because it is lazy and that causes a lot of confusion), so, you might want to add .view before it, and .toMap at the end:

    givvenMap.view.filterKeys {
      case X(_, `b1`, `c1`, `d1`) => true
      case _ => false
    }.toMap

Or better yet just:

   givvenMap.collect { case x@(X(_, `b1`, `c1`, `d1`), _) => x }

Upvotes: 1

Related Questions