How to filter a list in-place with Kotlin?

后端 未结 3 1572
孤街浪徒
孤街浪徒 2021-02-02 08:26

In Java I can remove items from a list with this code:

private void filterList(List items) {
    Iterator iterator = items.iterator();
           


        
3条回答
  •  走了就别回头了
    2021-02-02 08:57

    This will remove even numbers from the list 1-9, and prints [1, 3, 5, 7, 9]

    var myLists = mutableListOf(1,2,3,4,5,6,7,8,9)
    myLists.removeAll{ it % 2 == 0 }
    println(myLists)
    

    This will retain even numbers and remove others from the list 1-9, and prints [2, 4, 6, 8]

    myLists = mutableListOf(1,2,3,4,5,6,7,8,9)
    myLists.retainAll{ it % 2 == 0 }
    println(myLists)
    

    Try them in https://play.kotlinlang.org/

提交回复
热议问题