谓词为true时拆分列表 [英] Split list when predicate is true

查看:109
本文介绍了谓词为true时拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当特定谓词为true时,Kotlin是否提供突变功能来拆分列表?

Does Kotlin provide a mutation function to split a list when a specific predicate is true?

在以下示例中,当元素为.时,应拆分列表. 结果应为List<List<String>>类型.

In the following example the list should be split when the element is a .. The result should be of the type List<List<String>>.

// input list
val list = listOf(
    "This is", "the", "first sentence", ".",
    "And", "now there is", "a second", "one", ".",
    "Nice", "."
)

// the following should be the result of the transformation
listOf(
    listOf("This is", "the", "first sentence"),
    listOf("And", "now there is", "a second", "one"),
    listOf("Nice")
)

我需要类似list.splitWhen { it == "." }

推荐答案

Kotlin是否提供突变功能来在以下情况下拆分列表? 具体谓词是真的吗?

Does Kotlin provide a mutation function to split a list when a specific predicate is true?

我听说过的最接近的是 partition() ,但是我认为这不会对您有帮助.

The closest one I have heard of is partition(), however I don't think it will work in your case.

我已经制作并简要测试了3个高阶扩展函数,它们给出了相同的预期输出.

I have made and have briefly tested 3 higher order extension functions, which gives the same expected output.

解决方案1:直接方法

inline fun List<String>.splitWhen(predicate: (String)->Boolean):List<List<String>> {
    val list = mutableListOf<MutableList<String>>()
    var needNewList = false
    forEach {
            string->
        if(!predicate(string)){
            if(needNewList||list.isEmpty()){
                list.add(mutableListOf(string))
                needNewList= false
            }
            else {
                list.last().add(string)
            }
        }
        else {
            /* When a delimiter is found */
           needNewList = true
        }
    }
    return list
 }

解决方案2:基于配对的方法

inline fun List<String>.splitWhen(predicate: (String)->Boolean):List<List<String>> {
    val list = mutableListOf<List<String>>()
    withIndex()
        .filter { indexedValue ->  predicate(indexedValue.value) || indexedValue.index==0 || indexedValue.index==size-1} // Just getting the delimiters with their index; Include 0 and last -- so to not ignore it while pairing later on
        .zipWithNext() // zip the IndexValue with the adjacent one so to later remove continuous delimiters; Example: Indices : 0,1,2,5,7 -> (0,1),(1,2),(2,5),(5,7)
        .filter { pair-> pair.first.index + 1 != pair.second.index } // Getting rid of continuous delimiters; Example: (".",".") will be removed, where "." is the delimiter
        .forEach{pair->
            val startIndex = if(predicate(pair.first.value)) pair.first.index+1 else pair.first.index // Trying to not consider delimiters
            val endIndex = if(!predicate(pair.second.value) && pair.second.index==size-1) pair.second.index+1 else pair.second.index // subList() endIndex is exclusive
            list.add(subList(startIndex,endIndex)) // Adding the relevant sub-list
        }
    return list
}

解决方案3:如果定界符已找到方法,请检查下一个值

inline fun List<String>.splitWhen(predicate: (String)-> Boolean):List<List<String>> =
foldIndexed(mutableListOf<MutableList<String>>(),{index, list, string->
    when {
        predicate(string) -> if(index<size-1 && !predicate(get(index+1))) list.add(mutableListOf()) // Adds  a new List within the output List; To prevent continuous delimiters -- !predicate(get(index+1))
        list.isNotEmpty() -> list.last().add(string) // Just adding it to lastly added sub-list, as the string is not a delimiter
        else -> list.add(mutableListOf(string)) // Happens for the first String
    }
    list})

只需调用list.splitWhen{it=="delimiter"}.解决方案3看起来更像语法糖.除此之外,您还可以进行一些性能测试,以检查哪个性能良好.

Simply call list.splitWhen{it=="delimiter"}. Solution 3 looks more syntactic sugar. Apart from it, you can do some performance test to check which one performs well.

注意:我已经做了一些简短的测试,您可以通过科特琳游乐场或通过Github 要点.

Note: I have done some brief tests which you can have a look via Kotlin Playground or via Github gist.

这篇关于谓词为true时拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆