scala Remove (in place) all elements of a ListBuffer that meet a condition

前端 未结 2 2119
礼貌的吻别
礼貌的吻别 2021-02-13 04:26

I have a ListBuffer. I want to remove all elements that meet a certain condition.

I could iterate over it and remove each element. But what doe Scala say about mutating

2条回答
  •  执笔经年
    2021-02-13 05:03

    You can't do this efficiently, unfortunately. The implementation of --=(xs: TraversableOnce[A]) is (in expanded form; the actual code is more compact)

    xs foreach (x => this -= x) ; this
    

    which is just as inefficient as doing it one at a time (i.e. it's O(n*m) where n is the length of the original list and m is the number of items to remove).

    In general, the mutable collections don't have as full and powerful a set of methods as the immutable ones. (That is, they have all the wonderful methods used on immutable collections, but relatively few of their own.)

    So unless you're removing very few objects, you're probably better off filtering the list to create a new one.

提交回复
热议问题