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.
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.
removeIf() Return Value returns true if an element is removed from the arraylist.
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 true
by 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]
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