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
}