Java删除List里的元素

jdk1.8提供了一个removeIf的方法来对list进行删除操作:

public static void test(){
        List slist = new ArrayList<>();
        slist.add("111");
        slist.add("222");
        slist.add("333");
        slist.add("444");
        System.out.println(slist);
        slist.removeIf(s -> s.equals("333"));
        System.out.println(slist);

    }

控制台输出:

C:\java\jdk1.8.0\bin\java.exe "-javaagent:D:\idea\IntelliJ IDEA 1.16.18.jar 
[111, 222, 333, 444]
[111, 222, 444]

removeIf方法的源码就是使用迭代器遍历然后remove:

default boolean removeIf(Predicate filter) {
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator each = iterator();
        while (each.hasNext()) {
            if (filter.test(each.next())) {
                each.remove();
                removed = true;
            }
        }
        return removed;
    }

 

你可能感兴趣的:(java笔记)