迭代地图列表并进行转换

时间:2017-03-20 22:53:11

标签: scala

我对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);

在Scala中执行此操作时要遵循的最佳做法是什么?任何帮助或建议都会很棒!

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

使用Scala的map函数将列表元素(即Maps)转换为相应的连接键值:

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))

请注意,如果您决定将原始地图扩展为:

,则相同的功能将起作用
  Map("a" -> "A1", "b" -> "B1", c -> "C1", ...),
  Map("a" -> "A2", "b" -> "B2", c -> "C2", ...),
  ...