I found this:
fun main() {
val list: MutableList<Int> = mutableListOf(1, 2, 3, 4, 5)
list.removeAll { x -> x in 1..3 } // [4, 5]
list.removeIf { x -> x in 1..3 } // [4, 5]
}
Both of them yield the same result.
Though I understand that removeAll
is Kotlin and removeIf
is Java but I don't understand why removeAll
is there when removeIf
was already there?
And for the fact that we could use removeIf
in Kotlin without any hassle. Or is there any use case that might need one over another?
The Java ArrayList removeIf() method removes all elements from the arraylist that satisfy the specified condition. Here, arraylist is an object of the ArrayList class.
ArrayList removeIf() method in Java The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method. Errors or runtime exceptions are thrown during iteration or by the predicate are pass to the caller.
To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.
Java's removeIf()
is there since Java 1.8.
Kotlin started at 2011 (wikipedia). Java 1.8 appeared in 2014.
I'm not sure when the Kotlin's removeAll(predicate)
was specified and implemented, however it probably predates Java's removeIf()
.
There is one more important difference:
Calling removeIf
on a CopyOnWriteArrayList
is thread-safe, but removeAll
is not.
Looking at the code, removeIf
has a custom implementation for CopyOnWriteArrayList
, but removeAll
iterates over the indices and will end up throwing ArrayIndexOutOfBoundsException
or even worse, removing the wrong element, if called concurrently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With