Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - removeIf example

Tags:

java

lambda

HashMap<Integer, ArrayList<Integer>> cityMap = new HashMap<>();
...    
for (ArrayList<Integer> list : cityMap.values()) {
    int size = list.size();
    if (size > 0) {
        list.removeIf(i -> true);
    }
}

I don't quite understand what the removeIf does in this case. Especially the part (i -> true). Thank you for any explanation.

like image 604
Vaclav H. Avatar asked Apr 06 '17 05:04

Vaclav H.


People also ask

What is removeIf 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.

What does remove if return?

removeIf() Return Value returns true if an element is removed from the arraylist.


1 Answers

The Javadoc of removeIf() states:

Removes all of the elements of this collection that satisfy the given predicate.

The predicate in your example is always true because you map each integer i in your list to trueby the expression: i -> true.

I added a simpler example which removes all even integers and keeps all odd integers by the predicate i % 2 == 0:

Ugly setup:

List<List<Integer>> lists = new ArrayList<List<Integer>>() {{
    add(new ArrayList<>(Arrays.asList(1,2,3,4)));
    add(new ArrayList<>(Arrays.asList(2,4,6,8)));
    add(new ArrayList<>(Arrays.asList(1,3,5,7)));
}};

Keep only odd numbers:

for (List<Integer> list : lists) {
    list.removeIf(i -> i % 2 == 0);
    System.out.println(list);
}

Output:

[1, 3]
[]
[1, 3, 5, 7]
like image 147
Harmlezz Avatar answered Oct 27 '22 17:10

Harmlezz