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
Java - removeIf example
提问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 removeIf
does 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 true
because you map each integer i
in your list to true
by 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
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.
removeIf
将遍历列表中的每个元素并在其上运行指定的谓词(布尔函数)。如果谓词返回true
,它将从列表中删除。如果谓词返回false
,则不会。
In your case, every element will result in the predicate returning true
, thus clearing the list.
在您的情况下,每个元素都会导致谓词返回true
,从而清除列表。