有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

scala中的java多变量循环

我想在循环中迭代两个变量并填充映射。Java代码如下所示

for (int i = 0, j = 0; i < header.size(); i++, j++)
{
  map.put(header.get(i), cols.get(j));
}

我们如何在Scala实现这一点?有人能帮忙吗? 谢谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    一种方法是map在你的标题上加上每个条目的索引,获得同一索引的col并创建一个映射

    鉴于

    scala> val headers = Seq("h1", "h2", "h3", "h4")
    headers: Seq[String] = List(h1, h2, h3, h4)
    
    scala> val cols = Seq("c1", "c2", "c3")
    cols: Seq[String] = List(c1, c2, c3)
    

    当{}

    scala> headers.zipWithIndex.map{case (h, i) => h -> cols.lift(i).getOrElse("")}.toMap
    res50: scala.collection.immutable.Map[String,String] = Map(h1 -> c1, h2 -> c2, h3 -> c3, h4 -> "")
    

    如果headers.size == cols.size或者如果您不想要没有等价列的头,您可以使用list.zip(anotherList)

    scala> headers.zip(cols)
    res52: Seq[(String, String)] = List((h1,c1), (h2,c2), (h3,c3))
    
  2. # 2 楼答案

    在Scala中,您可以使用zip来实现这一点,比如:

    header.zip(cols).toMap