boolean removeIf(Object o):根据条件进行删除
源码:default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
原理:removeIf底层会遍历集合,得到集合中的每一个元素
使用方法:重写Predicate接口中的boolean test(T t)方法,t代表集合中的元素
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> c = new ArrayList<>();
c.add("hello");
c.add("world");
c.add("java");
c.add("PHP");
c.removeIf((String s) -> {
return s.length() == 3;
});
System.out.println(c);
}
s代表集合中的元素,根据重写的test方法判断该集合元素是否符合条件
如果返回值true,则删除
如果返回值false,则保留











