【问题标题】:Concatenate multiple list连接多个列表
【发布时间】:2016-03-31 13:03:04
【问题描述】:

我想知道如何使用循环连接多个列表。这是我正在尝试做的一个示例:

object MyObj {
  var objs = Set (
    MyObj("MyObj1", anotherObjList),
    MyObj("MyObj2", anotherObjList)
  )

  val list = List.empty[AnotherObj]
  def findAll = for (obj <- objs) List.concat(list, obj.anotherObjList)
}

我希望函数 findAll 连接来自集合 objs 对象的列表。

【问题讨论】:

    标签: scala collections


    【解决方案1】:

    试试这个:

    objs.flatMap(_.anotherObjList)
    

    它不使用for,但这可能是 Scala 中最简洁易读的方式。

    【讨论】:

      【解决方案2】:

      使用reduce

      类似这样的:

      objs.reduce((a,b) => a.anotherObjList ++ b.anotherObjList)
      

      或者如果Set 可以为空,请使用foldLeft

      objs.foldLeft(List.empty[AnotherObj],(a,b) => a.anotherObjList ++ b.anotherObjList)
      

      【讨论】:

      • 这不会编译。 aList 不是 MyObj
      • 为什么a 会是一个列表? objsSetMyObjss。
      • 我尝试了 reduce 方法,它不起作用。错误是类型不匹配;找到:List[AnotherObj],需要 MyObj
      【解决方案3】:

      在您的代码示例中,您使用的 val list 无法重新分配。当您执行List.concat(list, obj.anotherObjList) 时,您正在创建一个新列表,将空的list 连接到当前objanotherObjList,但结果 从未使用过,因此list 将执行for循环后仍然为空。

      如果您确实需要使用命令式 for 循环,请使用不可变集合并将其分配给 var,后者可以从 for 循环的主体中重新分配或使用可变集合:

      object MyObj {
        var objs = Set(
          MyObj("MyObj1", anotherObjList),
          MyObj("MyObj1", anotherObjList),
        )
      
        def findAllLoop1 = {
          var list = List.empty
          for (obj <- objs) list = list ++ obj.anotherObjList
          list
        }
      
        def findAllLoop2 = {
          val buf = collection.mutable.ListBuffer[Int]() // replace Int with your actual type of elements
          for (obj <- objs) buf ++= obj.anotherObjList
        }
      }
      

      但是,如果由于某种原因您不必使用命令式循环,我强烈建议您使用功能性替代方案:

      object MyObj {
        var objs = Set(
          MyObj("MyObj1", anotherObjList),
          MyObj("MyObj1", anotherObjList),
        )
      
        def findAll = 
          objs.flatMap(_.anotherObjList) // if Set as return type is okay
      
        def findAll: List[Int] = 
          objs.flatMap(_.anotherObjList)(collection.breakOut)  // if elements are of type Int and you want to get a List at the end, not a Set
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-08
        • 2018-12-19
        • 1970-01-01
        • 2012-10-22
        • 1970-01-01
        • 2010-10-21
        • 2018-05-11
        • 2022-01-09
        相关资源
        最近更新 更多