組合多個謂詞不起作用

用戶2498079

我正在嘗試從列表中篩選出某些項目,並按特定順序將它們合併到最終列表中。第一個代碼片段似乎效率低下,因為它創建了 2 個用於過濾的列表,然後迭代它們,但是該代碼有效。第二個片段試圖結合這兩種過濾,但是 map 操作符沒有將項目添加到 otherNums 列表

有人可以幫我理解為什麼會這樣嗎?

片段 1:

fun main() {
    val favItem = 0
    val list = listOf(11, 12, 13, 2,3,4,5,6,7,10, favItem)
    
    val greaterThan10 = list.filter{item -> item > 10}
    val otherNums = list.asSequence().filter{item -> item != favItem}.filter{item -> item < 10}
    
    println(" $greaterThan10") //the list is filled with proper numbers
    
    println("merged list ${greaterThan10.plus(favItem).plus(otherNums)}")
}

結果:

 [11, 12, 13]
merged list [11, 12, 13, 0, 2, 3, 4, 5, 6, 7]

片段 2:

fun main() {
    val favItem = 0
    val list = listOf(11, 12, 13, 2,3,4,5,6,7,10, favItem)
    
    val greaterThan10 = mutableListOf<Int>()
    val otherNums = list.asSequence().filter{item -> item != favItem}.map{
        if(it > 10) {
            greaterThan10.add(it)
        }
        it
    }
    .filter{item -> item != 10}
    
    println("$greaterThan10") // the list is empty
    
    println("merged list ${greaterThan10.plus(favItem).plus(otherNums)}")
}

結果:

 []
merged list [0, 11, 12, 13, 2, 3, 4, 5, 6, 7]
阿皮特·舒克拉

在您的第二個代碼段中,greaterThan10由於序列的惰性行為列表為空,只有在遇到類似toList()這樣的終端操作時才會迭代序列sum()

在您的情況下,當您編寫.plus(otherNums). List+Sequence產生一個List. 如果您greaterThan10在打印合併列表後打印您的列表,您會發現它已填充。

順便說一句,你不需要Sequence這裡。序列比列表更高效的兩種主要情況是:

  • 當你有很多中間操作時,比如mapfilter等等。創建Iterable了很多Iterable消耗更多內存的中間操作
  • 當你有某種短路操作在像年底take()contains()first()等即當整個集合不需要被重複以得到最終結果。

根據文檔,

序列的惰性增加了一些開銷,這在處理較小的集合或進行更簡單的計算時可能很重要。因此,您應該同時考慮 Sequence 和 Iterable 並決定哪一個更適合您的情況。

對於最終的解決方案,我認為您可以使用您的代碼段 1。這對我來說看起來不錯,只需刪除不必要的asSequence並將兩者合二為一filter

fun main() {
    val favItem = 0
    val list = listOf(11, 12, 13, 2, 3, 4, 5, 6, 7, 10, favItem)
    
    val greaterThan10 = list.filter {item -> item > 10}
    val otherNums = list.filter { it != favItem && it <= 10 }
    
    println(" $greaterThan10")
    
    println("merged list ${greaterThan10 + favItem + otherNums}")
}

我認為使用filterminus列表更好,因為後者俱有二次最壞情況時間複雜度(如果我沒記錯的話)。我寫了一個小例子來演示差異。運行幾次看到其中的差別。

此外,正如@IvoBeckers 在評論中提到的,“如果原始列表沒有 favItem,則此方法也會向其添加一個。如果列表中有多個 favItem,則此方法會將其替換為單個。”

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章