Scala 按最大值对列表中的字符串进行分组

Scala 按最大值对列表中的字符串进行分组,scala,Scala,我们一直试图在scala中解决这个问题,但还没有完全解决 我有一个列表[String],希望将不同的字符串组合在一起,这样就不会有超过最大大小的组,并在列表中记录它们的索引 以下是一些示例数据: val sample: List[String] = List[String]( "{\"test\":\"testfield\"}", // 20 length "{\"test2\":\"testfield2\"}", // 22 length "{\"test3\":\"t

我们一直试图在scala中解决这个问题,但还没有完全解决

我有一个
列表[String]
,希望将不同的字符串组合在一起,这样就不会有超过最大大小的组,并在列表中记录它们的索引

以下是一些示例数据:

val sample: List[String] = List[String](
    "{\"test\":\"testfield\"}", // 20 length
    "{\"test2\":\"testfield2\"}", // 22 length
    "{\"test3\":\"testfield3\"}") // 22 length

val maxLength = 48 // collect into groups where total .length is less than this

val output: List[List[Int]] =
    List(
        List(0,1),
        List(2)
    )
我已经成功地在Java中模拟了同样的东西,但是试图在没有for循环的情况下在Scala风格的代码中复制这一点比我强。我目前一直在尝试使用
scanleet


任何指向正确方向的指针都将不胜感激

这里有一个使用
foldLeft
的版本:

def groupByLength(list: List[String]): List[List[String]] = {
  list.foldLeft(List(List.empty[String])) { (acc, cur) => 
    if (acc.isEmpty) List(List(cur))
    else if (acc.last.map(_.length).sum + cur.length < maxLength) acc.init :+ (acc.last :+ cur)
    else acc :+ List(cur)
  }
}
对于更好的版本,可以使用
NonEmptyList
来保证生成的列表是有人居住的


如果您想返回列表的索引,可以事先
zipWithIndex

这基本上是换行操作,以前已经回答过了
List(
  List({"test":"testfield"}, {"test2":"testfield2"}), 
  List({"test3":"testfield3"})
)