2016-12-28 40 views
2

索引我有一個字符串轉換列表中的地圖與主要是在斯卡拉

val list = List("a", "b", "c", "d", "e") 

的名單,我想有一個與鍵在列表項的索引地圖。所以,我做了以下內容:

def mapByIndexes(list: List[String]): Map[Int, String] = (1 to list.size).zip(list).toMap 

然而,得到的地圖不保留索引順序和我得到這個結果:

Map(5 -> "e", 1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d") 

如何修改上面這樣的代碼我以下列自然順序獲得地圖?

Map(1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d", 5 -> "e") 

注:我知道,我可以排序生成的地圖,但我可以避開這一步,創建地圖已保留訂單嗎?

編輯:解決方案ListMap描述在Scala LinkedHashMap.toMap preserves order?的作品,但我不喜歡額外的括號和_*這麼簡單的事情。沒有別的,所以我可以鏈接?如果沒有,我會接受@pamu答案。

+1

[Scala LinkedHashMap.toMap保留順序的可能的重複?](http://stackoverflow.com/questions/6199186/scala-linkedhashmap-tomap-preserves-order) –

回答

3

我知道,我可以排序生成的地圖

不,你不能。排序Map沒有意義。但有自然順序存儲密鑰的Map實現,如TreeMapIntMap也是,IIRC)。請注意,它是而不是與保留廣告訂單一樣,因爲ListMapLinkedHashMap這樣做。

帶有在Scala中描述的ListMap的解決方案LinkedHashMap.toMap保留了訂單?工作,但我不喜歡附加的括號和_ *這麼簡單的事情。沒有別的,所以我可以鏈接?

沒有(至少,我不這麼認爲),但你可以很容易地定義它:

implicit class ToListMap[A, B](x: Seq[(A, B)]) { 
    def toListMap = ListMap(x: _*) 
} 

// somewhere where ToListMap is in scope or imported: 
val list = List(1 -> 2, 3 -> 4) 
list.toListMap 

注意ListMap基本上是一個列表(正如其名字),所以查詢它比任何合理的地圖實施都慢。

當然,你可以用TreeMap完全一樣。

+0

通過排序映射我的意思是你描述的東西。如果你谷歌的「排序地圖scala」它顯示這些:) –

+0

順便說一句,你提供的代碼不編譯。我得到'類型不匹配;找到:Seq [(A,B)]所需:(?,?)def toListMap = ListMap(x)' –

+0

嗨Alexey - 你爲什麼沒提到'SortedMap'?它沒有解決OP對按鍵排序的「map」的渴望嗎? –

2

使用ListMap。在壓縮而不是做toMap之後,只需構建保留元素順序的ListMap即可。您可以使用其伴侶對象構建一個ListMap。它接受元組的變量。

def mapByIndexes(list: List[String]): ListMap[Int, String] = ListMap((1 to list.size).zip(list): _*) 

斯卡拉REPL

scala> import scala.collection.immutable._ 
import scala.collection.immutable._ 

scala> def mapByIndexes(list: List[String]): ListMap[Int, String] = ListMap((1 to list.size).zip(list): _*) 
mapByIndexes: (list: List[String])scala.collection.immutable.ListMap[Int,String] 

scala> mapByIndexes(list) 
res10: scala.collection.immutable.ListMap[Int,String] = Map(1 -> a, 2 -> b, 3 -> c, 4 -> d, 5 -> e) 
+0

不錯,也適用於我。但我不喜歡附加的括號和'_ *'。沒有別的,所以我可以簡單地鏈接? –