Java - removeIf 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43246613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:14:40  来源:igfitidea点击:

Java - removeIf example

javalambda

提问by Vaclav H.

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 removeIfdoes in this case. Especially the part (i -> true). Thank you for any explanation.

我不太明白removeIf在这种情况下做什么。尤其是(i -> true)部分。谢谢你的任何解释。

回答by Harmlezz

The Javadoc of removeIf()states:

removeIf()状态的Javadoc :

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

删除此集合中满足给定谓词的所有元素。

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

您示例中的谓词始终true是因为您i将列表中的每个整数映射到true表达式:i -> true

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

我添加了一个更简单的示例,它通过谓词删除所有偶数并保留所有奇数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]

回答by Joe C

removeIfwill 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.

removeIf将遍历列表中的每个元素并在其上运行指定的谓词(布尔函数)。如果谓词返回true,它将从列表中删除。如果谓词返回false,则不会。

In your case, every element will result in the predicate returning true, thus clearing the list.

在您的情况下,每个元素都会导致谓词返回true,从而清除列表。