Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cases of removeall and removeif

Tags:

java

kotlin

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?

like image 791
Yogesh Avatar asked Aug 02 '18 12:08

Yogesh


People also ask

What does removeIf do in Java?

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.

How to use removeIf in Java ArrayList?

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.

How do I remove an object from a list in Java based on condition?

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.


2 Answers

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().

like image 109
Matej Avatar answered Oct 22 '22 10:10

Matej


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.

like image 40
Stefan Paul Noack Avatar answered Oct 22 '22 09:10

Stefan Paul Noack