Java - removeIf example

2020-02-15 00:25发布

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.

标签: java lambda
2条回答
手持菜刀,她持情操
2楼-- · 2020-02-15 00:34

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]
查看更多
ら.Afraid
3楼-- · 2020-02-15 00:34

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.

查看更多
登录 后发表回答