Home > Enterprise >  Scala how do i modify values in a Map[String, List[String, Set[String]]]
Scala how do i modify values in a Map[String, List[String, Set[String]]]

Time:10-31

I have a Map of type Map[String, List[(String, Set[String]])] eg : Map(ABC -> List((ABC, Set(X)))

I need to update it to Map[String, Set[String]]

Output : Map(ABC -> Set(X))

Mainly need to remove the List[String] Part from values.

CodePudding user response:

For example you can do .mapValues

val m: Map[String, List[(String, Set[String])]] = 
  Map("ABC" -> List(("ABC", Set("X"))))

// taking the set from the head of list, ignoring second "ABC"
val m1: Map[String, Set[String]] = m.view.mapValues(_.head._2).toMap
// Map(ABC -> Set(X))

// combining into union the sets from the whole list, ignoring second "ABC"
val m2: Map[String, Set[String]] =
  m.view.mapValues(_.map(_._2).fold(Set())(_ union _)).toMap
// Map(ABC -> Set(X))

// ignoring first "ABC"
val m3: Map[String, Set[String]] = m.values.flatten.toMap
// Map(ABC -> Set(X))

(m3 is courtesy of @Philluminati)

https://www.scala-lang.org/api/current/scala/collection/immutable/Map.html

https://docs.scala-lang.org/overviews/collections-2.13/maps.html

  • Related