Let's go over the existing map to the list of scala tuples

I have a list of tuples that I have to change the values ​​on the map containing these tuples. Therefore, if I have a list, such as List((0,2), (0,3))with a map that looks like this:, Map((0,2) => List(1,2,3), (0,3) => List(1,2))I need to access the corresponding sets of maps with tuples listed in the list, and then remove the number from the map.

So, in the above example, if I wanted to remove 2from the display, I would get Map((0,2) => List(1,3), (0,3) => List(1)).

The design is wise, I was thinking about a map matching template, but I read a few answers that said this wasn’t the best way. The tough part for me is that it should be immutable, so I thought of a template matching the list, getting the value of the map, changing the value, then re-creating the map and recursively calling the function again. What do you think of this implementation?

+4
source share
1 answer

This may be a way to remove 2from your Map:

val newMap = oldMap.mapValues(list => list.filter(_ != 2))

Or more generally:

def filterInMap(element: Int, oldMap: Map[(Int,Int),List[Int]]) = 
    oldMap.mapValues(list => list.filter(_ != element))

, - . mapValues Map , . filter , , , .

: :

def filterInMap[A](element: A, oldMap: Map[(A,A),List[A]]) = 
    oldMap.mapValues(list => list.filter(_ != element))
+2

All Articles