How to filter a list in-place with Kotlin?

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

    Just use .retainAll { ... } or .removeAll { ... }, both accepting a predicate, to filter it in-place:

    items.retainAll { shouldRetain(it) }
    

    items.removeAll { shouldRemove(it) }
    

    Note that items should be a MutableList for that, not just List, which is a read-only list in Kotlin and thus does not expose any mutating functions (see: Collections in the language reference).

    By the way, these two function are implemented efficiently for lists that support random access: then the list is not compacted after each item is removed (O(n2) time worst-case), and instead the items are moved within the list as it is processed, giving O(n) time.


    And if you don't want to modify the original list, you can produce a separate collection with only the items you want to retain using .filter { ... } or .filterNot { ... }, this will work for read-only List as well:

    val filtered = items.filter { shouldRetain(it) }
    

    val filtered = items.filterNot { shouldRemove(it) }
    

提交回复
热议问题