How to filter a list in-place with Kotlin?

后端 未结 3 1581
孤街浪徒
孤街浪徒 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:53

    Kotlin has a lot of neat built-in functions. You can try to use filter here.

    val filteredItems = items.filter { checkItem(it) }  
    

    Unfortunately, it will recreate the list. This API was designed on purpose to avoid extra mutability.

    But if you still want to proceed with a MutableList use retainAll method

    items.retainAll { checkItem(it) }
    

提交回复
热议问题