How to build a multimap from a list of tuples in Scala?

主宰稳场 提交于 2019-12-17 20:16:16

问题


Suppose I have a list of tuples List[(A, B)]. What is the best way to convert it to a multimap, which maps A to Set[B]? Can I build an immutable multimap ?


回答1:


Can I build an immutable multimap ?

Not with the MultiMap in Scala standard library. Of course, you can write your own.

What is the best way to convert it to a multimap?

import scala.collection.mutable.{HashMap, Set, MultiMap}

def list2multimap[A, B](list: List[(A, B)]) = 
  list.foldLeft(new HashMap[A, Set[B]] with MultiMap[A, B]){(acc, pair) => acc.addBinding(pair._1, pair._2)}



回答2:


I'm a bit confused, Multimap doesn't map A to Set[B], it maps A to B where B can have many values. Since you want something immutable, I'm going to change this to Map[A, Set[B]] which isn't a Multimap but does one of the things you said you wanted.

// This is your list of (A, B)
val l = List((1, "hi"),
             (2, "there"),
             (1, "what's"),
             (3, "up?"))
// Group it and snip out the duplicate 'A'
// i.e. it initially is Map[A, List[(A, B)]] and we're going to convert it
// to Map[A, Set[B]]
val m = l.groupBy(e => e._1).mapValues(e => e.map(x => x._2).toSet)
println(m)
// Prints: Map(3 -> Set(up?), 1 -> Set(hi, what's), 2 -> Set(there))


来源:https://stackoverflow.com/questions/7209807/how-to-build-a-multimap-from-a-list-of-tuples-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!