Scala如何修改Map中的值[字符串,列表[字符串,集合[字符串]]

vybvopom  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(234)

我有一张Map[String, List[(String, Set[String]])]类型的Map,例如:Map(ABC -> List((ABC, Set(X)))
我需要将其更新为Map[String, Set[String]]
输出:Map(ABC -> Set(X))
主要需要从值中删除List[String]部分。

vmdwslir

vmdwslir1#

例如,您可以使用.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由**@Philllightati**提供)
https://www.scala-lang.org/api/current/scala/collection/immutable/Map.html
https://docs.scala-lang.org/overviews/collections-2.13/maps.html

相关问题