Java_collection 集合框架
通过下面例子学习collection接口的RemoveIf方法;Iterator接口forEachRemaining方法
package cn.ling.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//collection 接口 removeIf方法 删除满足某个条件的元素
public class RemoveIf {
public static void main(String[] args) {
List<String> strList = new ArrayList<>();
strList.add("apple");
strList.add("apple1");
strList.add("apple2");
strList.add("apple3");
strList.add("apple4");
strList.add("banana");
strList.add("1banana");
strList.add("2banana");
strList.add("3banana");
strList.add("43banana");
Iterator<String> iterators = strList.iterator();
while (iterators.hasNext()){
System.out.print(iterators.next()+ " ");
}
System.out.println();
System.out.println("--------------------------------");
strList.iterator().forEachRemaining((str)-> System.out.print(str+ " "));
strList.removeIf((str)-> str.startsWith("a"));
System.out.println();
System.out.println("--------------------------------");
strList.iterator().forEachRemaining((str)->System.out.print(str+ " "));
}
}
这个两个方法都要是用到Lambda表达式。
forEachRemaining
相当于循环执行目标函数的实现
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
//执行目标函数的函数体 Consumer是函数式接口
action.accept(next());
}
strList.iterator().forEachRemaining((str)-> System.out.print(str+ " "));
上面写法不懂,可以参考:https://blog.csdn.net/lingyiwin/article/details/109212540
removeIf
实现过滤筛选的功能
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
//如果匹配成功 执行remove方法
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}