Java-removeIf示例 [英] Java - removeIf example
本文介绍了Java-removeIf示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HashMap<Integer, ArrayList<Integer>> cityMap = new HashMap<>();
...
for (ArrayList<Integer> list : cityMap.values()) {
int size = list.size();
if (size > 0) {
list.removeIf(i -> true);
}
}
在这种情况下,我不太了解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()
的Javadoc指出:
The Javadoc of removeIf()
states:
删除此集合中满足给定谓词的所有元素.
Removes all of the elements of this collection that satisfy the given predicate.
您的示例中的谓词始终为true
,因为您使用表达式i -> true
将列表中的每个整数i
映射到true
.
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 % 2 == 0
删除所有偶数整数并保留所有奇数整数:
I added a simpler example which removes all even integers and keeps all odd integers by the predicate i % 2 == 0
:
丑陋的设置:
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)));
}};
仅保留奇数:
for (List<Integer> list : lists) {
list.removeIf(i -> i % 2 == 0);
System.out.println(list);
}
输出:
[1, 3]
[]
[1, 3, 5, 7]
这篇关于Java-removeIf示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文