Scala 连接多个列表

Scala 连接多个列表,scala,collections,Scala,Collections,我想知道如何使用循环连接多个列表。下面是我尝试做的一个例子: 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.anotherObjLi

我想知道如何使用循环连接多个列表。下面是我尝试做的一个例子:

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)
}
对象MyObj{
var objs=Set(
MyObj(“MyObj1”,另一个目标列表),
MyObj(“MyObj2”,另一个目标列表)
)
val list=list.empty[AnotherObj]
def findAll=for(obj尝试以下方法:

objs.flatMap(_.anotherObjList)

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

使用
reduce

大概是这样的:

objs.reduce((a,b) => a.anotherObjList ++ b.anotherObjList)
或者,如果
集合
可以为空,请使用
foldLeft

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

在您的代码示例中,您使用的是无法重新分配的
val
列表
您正在创建一个新列表,该列表将空的
列表
关联到当前的
obj
另一个对象列表
,但结果从未使用过,因此执行for循环后
列表仍将为空

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

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

这不会编译。
a
是一个
List
不是
MyObj
为什么
a
是一个List?
objs
MyObjs
s的
集合。我尝试过reduce方法,但不起作用。错误是类型不匹配;发现:List[AnotherObj],需要MyObj
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
}