列表的Scala HashMap:更简单的默认? [英] Scala HashMap of Lists: simpler default?

查看:107
本文介绍了列表的Scala HashMap:更简单的默认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个HashMap的列表。通常我这样做:

I need a HashMap of Lists. Normally I do this:

val lists = mutable.HashMap[String,List[Int]]() { 
  override def default(key: String) = {
    val newList = List[Int]()
    this(key) = newList
    newList
  }
}

,这样我就可以简单地写出像

so that I can then simply write things like

lists("dog") ::= 14

不必担心狗列表是否已经初始化。

without having to worry about whether the "dog" List has been initialised yet.

有没有更简单的方法来做到这一点?

Is there a cleaner way to do this? I find myself typing out those five default override lines again and again.

谢谢!

Thanks!

推荐答案

val lists = new mutable.HashMap[String,List[Int]].withDefaultValue(Nil)

lists("dog") ::= 13
lists("cat") ::= 14
lists("dog") ::= 15  //(13, 15)



另见




  • 如何使用默认操作实现Map在Scala

  • See also

    • How to implement Map with default operation in Scala
    • 这篇关于列表的Scala HashMap:更简单的默认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆