我想把一个列表分成几个子列表,但是我不知道怎么做。有一次,我的想法是按元素索引来划分列表。对于实例"B“索引是0,"S”索引2,所以我想把索引0-1之间的一部分放到第一个子列表中,然后第二个子列表应该是索引2-5之间的部分。
val listOfObj = listOf("B", "B" , "S", "B", "B", "X", "S", "B", "B", "P")分裂后的结果:
listOf(listOf("B","B"), listOf("S", "B", "B", "X"), listOf("S", "B", "B", "P") )怎样才能达到这样的结果呢?
发布于 2018-11-10 10:01:55
开始吧。我是在没有检查的情况下从手机上写的,但这个想法是基本的。
val result = mutableListOf<List<String>>()
var current = mutableList<String>()
listOfObj.forEach { letter ->
if (letter == "S") {
result.add(current)
current = mutableListOf<String>()
}
current.add(letter)
}
if (current.isNotEmpty()) {
result.add(current)
}您甚至可以为List<T>创建一个扩展函数,该函数将分隔符元素作为参数并返回列表列表。
https://stackoverflow.com/questions/53233624
复制相似问题