2017-03-20 111 views
0

我非常新Scala和努力學習一些東西,想了解下面的最佳做法:迭代的地圖列表和轉化

我有地圖下面的列表。

List<Map<String,String>> listOfMaps = new ArrayList<>(); 
Map<String,String> map1 = new HashMap<>(); 
map1.put("a","A1"); 
map1.put("b","B1"); 
. 
. 
. 
map10.put("a","A10"); 
map10.put("b","B10"); 

listOfMaps.add(map1); 
listOfMaps.add(map2); 
... 
listOfMaps.add(map10); 

我想重複這一點,從地圖變換到另一個列表只是一個特定的鍵,值對,並添加一個新值

List<Map<String,String>> newlistOfMaps = new ArrayList<>(); 
    for(Map map: listOfMaps) { 
     Map<String,String> newMap = new HashMap<>(); 
     newMap.put("a_b", map.get("a")+"_"+map.get("b")); 
     newListOfMaps.add(newMap); 
    } 

    System.out.println(newListOfMaps); 

什麼是最好的實踐遵循而在斯卡拉這樣做?任何幫助或建議都會很棒!

回答

1

這看起來像你正在尋找? 關注語法 - 您會注意到在Scala中構建List和Map比在Java中更容易。

scala> val listOfMaps: List[Map[String, String]] = List(
    Map("a" -> "A1", "b" -> "B1"), 
    Map("a" -> "A2", "b" -> "B2"), 
    Map("a" -> "A3", "b" -> "B3") 
) 
listOfMaps: List[Map[String,String]] = List(Map(a -> A1, b -> B1), Map(a -> A2, b -> B2), Map(a -> A3, b -> B3)) 

scala> val mapsCombined: List[Map[String, String]] = listOfMaps.map{ m => 
    Map("a_b" -> s"${m.apply("a")}_${m.apply("b")}") // string interpolation to avoid String concatenation 
} 
mapsCombined: List[Map[String,String]] = List(Map(a_b -> A1_B1), Map(a_b -> A2_B2), Map(a_b -> A3_B3)) 

mapsCombined我們可以做

listOfMaps.map{ m => 
    Map("a_b" -> s"${m("a")}_${m("b")}") 
} 
// no .apply as calling with the paren directly is it's equivalent in Scala, also the same as .get on Java. 
0

使用Scala的地圖功能列表中的元素(即地圖)轉變成其相應的級聯鍵值:

scala> val mapList: List[Map[String, String]] = List(
    Map("a" -> "A1", "b" -> "B1"), Map("a" -> "A2", "b" -> "B2"), Map("a" -> "A3", "b" -> "B3") 
) 

mapList: List[Map[String,String]] = List(Map(a -> A1, b -> B1), Map(a -> A2, b -> B2), Map(a -> A3, b -> B3)) 

scala> val newMapList: List[Map[String, String]] = mapList.map(m => 
    Map(m.keys.mkString("_") -> m.values.mkString("_")) 
) 

newMapList: List[Map[String,String]] = List(Map(a_b -> A1_B1), Map(a_b -> A2_B2), Map(a_b -> A3_B3)) 

注意,如果您決定將原始Google地圖擴大爲,可以使用相同的功能,例如:

Map("a" -> "A1", "b" -> "B1", c -> "C1", ...), 
    Map("a" -> "A2", "b" -> "B2", c -> "C2", ...), 
    ...