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 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]
removeIf
will go through each element in your list and run the specified predicate (boolean function) on it. If the predicate returns true
, it will be removed from the list. If the predicate returns false
, it will not.
In your case, every element will result in the predicate returning true
, thus clearing the list.