如何将Int或Long连接到Scala中的列表?

时间:2017-12-06 22:58:27

标签: scala

我有这个:

val vertexIdListPartitions: TrieMap[Long, List[Long]]

我需要这样的事情:

vertexIdListPartitions(0) - > List[2,3,4,5,etc..]

但是当我以这种方式在列表中添加数字时:

for(c<- 0 to 10)
   vertexIdListPartitions.update(0,List(c))

结果为List[10]

我怎么能连接它们?

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你不需要for循环:

import scala.collection.concurrent.TrieMap

val vertexIdListPartitions = TrieMap[Long, List[Long]]()

vertexIdListPartitions.update(0, (0L to 10L).toList)
// res1: scala.collection.concurrent.TrieMap[Long,List[Long]] = 
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

[UPDATE]

以下是相应地向tuple添加或连接键值TrieMap的方法:

def concatTM( tm: TrieMap[Long, List[Long]], kv: Tuple2[Long, List[Long]] ) =
  tm += ( tm.get(kv._1) match {
    case Some(l: List[Long]) => (kv._1 -> (l ::: kv._2))
    case None => kv
  } )

concatTM( vertexIdListPartitions, (1L, List(1L, 2L, 3L)) )
// res2: scala.collection.concurrent.TrieMap[Long,List[Long]] =
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 1 -> List(1, 2, 3))

concatTM( vertexIdListPartitions, (0L, List(11L, 12L)) )
// res61: scala.collection.concurrent.TrieMap[Long,List[Long]] = 
// TrieMap(0 -> List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 1 -> List(1, 2, 3))