操作员要从Kotlin的集合中删除先前的元素吗?

时间:2019-07-09 15:15:47

标签: kotlin collections

我有以下列表:

val headersAndContent = mutableListOf(..., Pair(1, "header"), Pair(2, "header"), Pair(3, "content for 2"), ...)

我想删除所有header类型的元素,其后没有内容元素。

因此,通过应用此类运算符结果列表将如下所示:

(..., Pair(2, "header"), Pair(3, "content for 2"), ...)

我想知道这样的运算符是否存在吗?

2 个答案:

答案 0 :(得分:1)

@Francesc的回答为解决您的问题提供了一个很好的实用方法。但是,如果您(或其他任何人)想要采用功能更强大的编程范例的解决方案,请考虑使用此代码

typealias CustomData = Pair<Int, String>

private fun CustomData.isHeader() = second == "header"
private fun CustomData.isContent() = !isHeader()

fun dropUnwantedHeaders(data: List<CustomData>) =
    data.asSequence()
    // add a duplicate of the last element to the list. this is an easy way in this case to deal with the problem that the map operation
    // is not the exact inverse of the zipWithNext operation
    .plusElement(data.last())
    // combine each element with the one after it since the filter predicate depends on both
    .zipWithNext()
    .filterNot { (elem, nextElem) ->
        // drop element if it is a header and the subsequent element is not content
        elem.isHeader() && !nextElem.isContent()
    }
    // undo the previous zip operation. this results in dropping the last element of the list
    .map { it.first }
    .toList()

fun main() {
    val unfilteredData = listOf(Pair(1, "header"), Pair(2, "header"), Pair(3, "content for 2"))
    val expectedResult = listOf(Pair(2, "header"), Pair(3, "content for 2"))
    assert(dropUnwantedHeaders(unfilteredData) == expectedResult)
}

答案 1 :(得分:0)

类似这样的东西

list.removeAll {
    val index = list.indexOf(it)
    "header" == it.second && index < list.size - 1 && "content" == list[index + 1].second 
}

您可能需要调整“是否满足”要求。